SQL 按月进行数据透视和分组

SQL pivot and group by month

我正在尝试获取每月的生产总和并将月行转为列。你能告诉我这段代码有什么问题吗?'

select *
from (
    select datename(month,day), UnitId, sum(pv_production) as production, year(day)
    from MeterReading
    group by datename(month,day), UnitId, year(day))  p
    pivot ( 
        max(pv_production) for datename(month, day) in ([January], [February], [March], [April], [May], [June], [July], [August], [September], [October], [November], [December]
    )
) as pp

您的查询中有多项错误。列需要别名,并且 PIVOT 中的 max() 引用了无效的列名

Select *
  From (
        Select [Month] = datename(month,day)
             , [Year]  = year(day)
             , UnitId
             , production = sum(pv_production) 
         From  MeterReading
         Group By datename(month,day)
                 ,year(day)
                 ,UnitId 
       )  Src
 Pivot ( max(production) for [Month] in ([January]
                                        ,[February]
                                        ,[March]
                                        ,[April]
                                        ,[May]
                                        ,[June]
                                        ,[July]
                                        ,[August]
                                        ,[September]
                                        ,[October]
                                        ,[November]
                                        ,[December] ) ) Pvt