获取按特定字段分组的每个月的值总和

时间:2016-06-29 22:53:44

标签: sql sql-server-2012 group-by

我在SQL Server 2012中有一个视图,它显示了一些项目的事务,如下所示:

项目交易简化视图样本

enter image description here

我需要显示每个月中每件商品的总费用总和(数量乘以费用),并将月份显示为以下列

enter image description here

1 个答案:

答案 0 :(得分:1)

试试这个。

dateDf$ReagentType <- typeDf$ReagentType[as.numeric(cut(dateDf$Date, 
                                                 breaks = typeDf$Date))]

对于动态查询月和年

SELECT  * FROM (SELECT  
            SUM(Cost) AS Cost, 
            CONVERT(VARCHAR(3), DATENAME(MONTH, DATEADD(MONTH, MONTH(MonthCol), - 1))) MonthCol
            FROM myTable WHERE YEAR(MonthCol) = 2016
            GROUP BY  MonthCol) AS TP
     PIVOT (SUM(Cost) FOR MonthCol IN ([Jan], [Feb], [Mar], [Apr], [May], [Jun], [Jul], [Aug], [Sep], [Oct], [Nov], [Dec])) AS PVTTable