1

仍然在 SQL 上咬牙切齿。这是我目前的查询(我将在以后扩展它以包括所有月):

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
4

1 回答 1

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

于 2013-04-28T17:45:01.553 回答