MySQL版本,可參考
思路:
SELECT
name_table.`name`,
month_table.`date`,
IFNULL(demo.`count`, 0) AS `count`
FROM
(
SELECT
`date`
FROM
demo
GROUP BY `date`
) month_table
INNER JOIN
(
SELECT
`name`
FROM
demo
GROUP BY `name`
) name_table
LEFT JOIN
demo ON
month_table.`date` = demo.`date` AND
name_table.`name` = demo.`name`
ORDER BY
name_table.`name`,
month_table.`date`
CREATE TABLE `demo` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
`date` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
`count` int NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
INSERT INTO `demo` VALUES (1,'紅茶','2020-01',800),(2,'紅茶','2020-02',750),(3,'紅茶','2020-03',900),(4,'綠茶','2020-01',900),(5,'綠茶','2020-02',850),(6,'綠茶','2020-03',900),(7,'青茶','2020-01',700),(8,'青茶','2020-03',900);
有幫助到你請給個最佳解答
看錯題目了
自刪
不是一個欄位 NULL 要顯示成 0
而是「少了一筆資料」要補進去青茶 2021-02 0
我不會
CREATE TABLE TableX(
A text(20), -- 品名
B text(20), -- 月份
C int); -- 銷售量
INSERT INTO TableX (A,B,C) values
('紅茶','2021-01',800),
('紅茶','2021-02',750),
('紅茶','2021-03',900),
('綠茶','2021-01',900),
('綠茶','2021-02',850),
('綠茶','2021-03',900),
('青茶','2021-01',700),
('青茶','2021-03',900);
CREATE TABLE TableY(
A text(20)); -- 品名
INSERT INTO TableY (A) values
('紅茶'),
('綠茶'),
('青茶'),
-- 額外增加
('烏龍茶');
-- MySQL 8
SELECT TempK.A AS '品名',TempM.MonthID AS '月份',IFNULL(TableX.C, 0) AS '銷售量'
FROM (
WITH RECURSIVE cte_count (n)
AS (
SELECT 1
UNION ALL
SELECT n + 1
FROM cte_count
WHERE n < 12
)
SELECT n,
CONCAT('2021-',LPAD(CONCAT(n, ''),2,0)) AS 'MonthID'
FROM cte_count
-- 計算到 3 月
WHERE n<=3
) AS TempM
LEFT JOIN (
SELECT A
FROM TableY
) AS TempK ON 1=1
LEFT JOIN TableX ON TableX.B=TempM.MonthID AND TableX.A=TempK.A
ORDER BY TempK.A,TempM.MonthID
-- 非 MySQL 8
SELECT TempK.A AS '品名',TempM.MonthID AS '月份',IFNULL(TableX.C, 0) AS '銷售量'
FROM (
-- 計算到 3 月
SELECT '2021-01' AS 'MonthID'
UNION
SELECT '2021-02' AS 'MonthID'
UNION
SELECT '2021-03' AS 'MonthID'
) AS TempM
LEFT JOIN (
SELECT A
FROM TableY
) AS TempK ON 1=1
LEFT JOIN TableX ON TableX.B=TempM.MonthID AND TableX.A=TempK.A
ORDER BY TempK.A,TempM.MonthID