1

大家好,我有一个类似以下的数据库:

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

谢谢。

4

2 回答 2

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

于 2013-05-31T07:18:10.747 回答
2

您通常会使用rollup或类似的子句来执行此操作:

select DateTime, sum(amount) as Amount, coalesce(country, 'Total')
from t
group by rollup(country), DateTime
于 2013-05-31T07:25:25.190 回答