仍在削减我的牙齿。这是我目前的查询(我会将其扩展为包含所有月份):
SELECT catid,
CASE WHEN MONTH(expdate) = '1' then SUM(expamount) END AS 'january',
CASE WHEN MONTH(expdate) = '2' then SUM(expamount) END AS 'february',
CASE WHEN MONTH(expdate) = '4' then SUM(expamount) END AS 'april'
FROM users LEFT JOIN (expcategories INNER JOIN expenses ON catid = catid_fk)
ON userid=userid_fk WHERE userid='1' GROUP BY catid, MONTH(expdate)
catid January February April
1 123.0000 NULL NULL
2 NULL 500.000 NULL
1 NULL NULL 505.0000
我希望特定catid
的结果在单行返回,例如:
catid January February April
1 123.0000 NULL 505.0000
2 NULL 500.000 NULL
答案 0 :(得分:3)
简单回答:从MONTH(expdate)
子句中删除GROUP BY
,并移动每个SUM
以包含其CASE
子句 - 如下所示:
SELECT catid,
SUM(CASE WHEN MONTH(expdate) = '1' then expamount END) AS 'january',
SUM(CASE WHEN MONTH(expdate) = '2' then expamount END) AS 'february',
SUM(CASE WHEN MONTH(expdate) = '4' then expamount END) AS 'april'
FROM users
LEFT JOIN (expcategories INNER JOIN expenses ON catid = catid_fk)
ON userid=userid_fk WHERE userid='1'
GROUP BY catid
(或者,考虑使用SQLServer的PIVOT
功能。)