如何使用数据透视功能,使用datepart字段

时间:2015-03-19 16:50:13

标签: sql sql-server sql-server-2008 date pivot

  

当前输出

WeekNumber WeeklyCount 11 100 10 200 9 300 8 400 7 500

  

期望输出

WeekNumber   11  10   9   8   7
WeeklyCount 100 200 300 400 500
  

当前查询:

SELECT Top 5     DatePart(ww, DATE) as weekNumber, Count(id) as WeeklyCount
    FROM         dbo.AL
   Where DatePart(ww, DATE) <> DatePart(ww, GetDate())
    group by  DatePart(ww, DATE)
    order by DatePart(ww, DATE) desc
  

如何使用pivot功能返回所需的输出?

Pivot function query

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT [11], [10], [9], [8], [7]
FROM (YourQueryHERE) AS DT
PIVOT(SUM(WeeklyCount) FOR WeekNumber IN([11], [10], [9], [8], [7])) AS PT

如果您想要动态版,请参阅我的评论;)