SQL Server:Group By和Pivot

时间:2017-08-01 07:44:01

标签: sql-server tsql

我正在编写一个SQL Server查询来提取数据。

例如我的查询:

SELECT 
    DATEPART(Year, capDateTime) Year, 
    DATEPART(Month, capDateTime) Month, 
    SUM(CAST(amount AS MONEY)) [TotalAmount]
FROM 
    dbo.iso_main
GROUP BY 
    DATEPART(Year, capDateTime), DATEPART(Month, capDateTime)
ORDER BY 
    Year, Month 

结果如下:

enter image description here

现在,我一直在质疑自己如何得到这样的结果:

|Month 7    | Month 8    |
+-----------+------------+
| 726800.00 | 2208400.00 |

我真的不关心这一年,我只是想让它回归几个月。

1 个答案:

答案 0 :(得分:3)

像这样使用PIVOT

SELECT *
FROM (
    SELECT 
        year(capDateTime) as [year],left(datename(month,icapDateTime),3)as [month], 
        CAST(amount AS money) as Amount 
    FROM dbo.iso_main
) as s
PIVOT
(
    SUM(Amount) 
    FOR [month] IN (jan, feb, mar, apr, 
    may, jun, jul, aug, sep, oct, nov, dec)
)AS pvt

检查this link以便进一步阅读。