我正在尝试创建一个按描述对项目进行分组的查询,然后计算过去3个月的项目,每个月都有自己的列。最终,我正在努力实现以下目标:
+-------------+------------+------------+--------------------+ | Description | This Month | Last Month | The Previous Month | +-------------+------------+------------+--------------------+ | Item_1 | 4 | 3 | 5 | | Item_2 | 3 | 0 | 2 | | Item_3 | 1 | 3 | 5 | +-------------+------------+------------+--------------------+
答案 0 :(得分:1)
SELECT
"Description",
SUM(
CASE
WHEN "Date" > NOW() THEN 0
WHEN "Date" > NOW() - INTERVAL 1 MONTH THEN 1
ELSE 0
END CASE
) AS "This month",
SUM(
CASE
WHEN "Date" > NOW() - INTERVAL 1 MONTH THEN 0
WHEN "Date" > NOW() - INTERVAL 2 MONTH THEN 1
ELSE 0
END CASE
) AS "Last month",
SUM(
CASE
WHEN "Date" > NOW() - INTERVAL 2 MONTH THEN 0
WHEN "Date" > NOW() - INTERVAL 3 MONTH THEN 1
ELSE 0
END CASE
) AS "The previous month"
FROM Items
WHERE "Date" > NOW() - INTERVAL 3 MONTH
GROUP BY "Description"