如何使用pivot并具有2个不同的聚合函数?

时间:2016-04-01 09:05:10

标签: sql sql-server sql-server-2014

我有一个包含1个日期列的表。我想按年和月分组日期,以便我有一个矩阵,如:

Year Jan Feb Mar...Dec Total
2015.....
2016  10  15  10... 10   115
2017.....

使用PIVOT函数是否可以实现,以及我如何使用它来实现上述目标?

2 个答案:

答案 0 :(得分:2)

你可以在没有PIVOT的情况下实现

SELECT
   DATEPART(yyyy,t.the_date) as year,
   SUM(CASE WHEN DATEPART(mm,t.the_date)=1 THEN 1 ELSE 0 END) as Jan,
   SUM(CASE WHEN DATEPART(mm,t.the_date)=2 THEN 1 ELSE 0 END) as Feb,
...
   SUM(CASE WHEN DATEPART(mm,t.the_date)=12 THEN 1 ELSE 0 END) as Dec,
   COUNT(*) as Total
FROM the_table t
GROUP BY DATEPART(yyyy,t.the_date)

答案 1 :(得分:1)

尝试使用此查询: -

SELECT *
    FROM (
        SELECT 
            year(yourDate) as [year],left(datename(month,yourDate),3)as [month], 
            Amount 
        FROM YourTableName
    ) as s
    PIVOT
    (
        SUM(Amount)
        FOR [month] IN (jan, feb, mar, apr, 
        may, jun, jul, aug, sep, oct, nov, dec)
    )AS pvt