在MSSQL中按类别汇总每日总数

时间:2013-05-31 07:15:26

标签: sql sql-server

大家好我有一个数据库,如下所示:

TransactionID     DateTime        Amount      Country
-----------------------------------------------------
T123456           2013-05-01         100           US
T123457           2013-05-01         150           US
T123458           2013-05-01         200           CN
T123459           2013-05-01         250           CN
T123460           2013-05-02         250           TW
T123461           2013-05-02         350           ID
T123462           2013-05-02         200           TW
T123463           2013-05-02          50           ID
T123464           2013-05-02         250           TW
T123465           2013-05-03         450           TW
T123466           2013-05-03         350           ID
T123467           2013-05-03         200           TW
T123468           2013-05-03         150           CN
T123469           2013-05-03         350           US

是否可以使用MSSQL产生以下结果?

DateTime        Amount      Country
-----------------------------------
2013-05-01         700        Total
2013-05-01         450           CN
2013-05-01         250           US
2013-05-02        1100        Total
2013-05-02         700           TW
2013-05-02         400           ID
2013-05-03        1500        Total
2013-05-03         650           TW
2013-05-03         350           ID
2013-05-03         350           US
2013-05-03         150           CN

感谢。

2 个答案:

答案 0 :(得分:3)

带一点UNION

SELECT u.DateTime, u.Amount, u.Country 
FROM (
SELECT DateTime, SUM(Amount) as Amount, Country
FROM Table1
GROUP BY DateTime, Country
UNION
SELECT DateTime, SUM(Amount) as Amount, 'Total' as Country
FROM Table1
GROUP BY DateTime) u
ORDER BY u.Datetime,
CASE WHEN u.Country = 'Total' THEN 0 else 1 END,
u.Country

SqlFiddle

答案 1 :(得分:2)

您通常会使用rollup或类似条款执行此操作:

select DateTime, sum(amount) as Amount, coalesce(country, 'Total')
from t
group by rollup(country), DateTime