-1

我正在尝试创建一个查询,该查询将按描述对项目进行分组,然后计算过去 3 个月的项目,每个月都有自己的列。最终,我试图实现以下目标:

    +-------------+------------+------------+--------- ------------+
    | 说明 | 本月 | 上个月 | 上个月 |
    +-------------+------------+------------+--------- ------------+
    | 项目_1 | 4 | 3 | 5 |
    | 项目_2 | 3 | 0 | 2 |
    | 项目_3 | 1 | 3 | 5 |
    +-------------+------------+------------+--------- ------------+
4

1 回答 1

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"
于 2013-04-07T01:32:11.763 回答