- 此问题在此处已有答案**:
How to fill missing dates with time in range?(1个答案)
昨天关门了。
我需要获取月份的所有统计信息,但有些月份在表中没有记录。
SELECT `nationality` AS `nationality`,
MONTHNAME((booked_date)) AS `MonthName`,
COUNT(*) AS `dataCount`,
MONTH(booked_date) AS `MonthNumber`,
YEAR(booked_date) AS `YearNumber`,
SUM(amount) AS `amount`
FROM bookings
WHERE YEAR(booked_date) = '2023'
AND MONTH(booked_date) = '1'
GROUP BY `MonthName`,`nationality`
ORDER BY `dataCount` DESC
LIMIT 1
我已经尝试过了,但我只得到了选定的月份,我需要得到该年的所有记录,即使该月份不存在于表中
CREATE TABLE `bookings` (
`booking_id` int(11) NOT NULL,
`full_name` varchar(255) NOT NULL,
`birthYear` int(11) NOT NULL,
`nationality` varchar(255) NOT NULL,
`group` varchar(255) NOT NULL,
`booked_by` int(11) DEFAULT NULL,
`booked_date` date NOT NULL,
`booked_on` date NOT NULL,
`booking_ref` varchar(255) DEFAULT NULL,
`amount` decimal(12,2) NOT NULL,
`status` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
1条答案
按热度按时间s4n0splo1#
使用您提供的架构:
您可以使用CTE(公用表表达式)构建月份列表,然后在这些月份上使用
LEFT JOIN
:输出如下所示: