SQL将行合并为单行

时间:2013-04-28 17:38:13

标签: sql sql-server

仍在削减我的牙齿。这是我目前的查询(我会将其扩展为包含所有月份):

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

1 个答案:

答案 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功能。)