我在SQL Server 2014中有一个使用此架构的表:
OccuredDate (date) TypeID (int)
2014-1-1 1
2014-1-2 1
2014-2-5 4
2015-5-23 2
2015-6-3 3
...它有数千行由日期和时间组成。 typeIDs,跨越多年。
因此,我可以将其绘制为图表组件,我正在尝试构建一个查询,在给定年份 1)每月返回一行 2)计算给定TypeID的TypeID实例总数。图表组件更喜欢列类型计数。
所以对于" 2014"它看起来像这样:
MonthDate TypeOne TypeTwo TypeThree TypeFour
2014-1-1 2 0 0 0
2014-2-1 0 0 0 1
或:
Year Month TypeOne TypeTwo TypeThree TypeFour
2014 Jan 2 0 0 0
2014 Feb 0 0 0 1
大部分时间都花在它上面,但没有运气。是否有一些黑暗的SQL魔法可以做到这一点?
谢谢!
答案 0 :(得分:7)
您可以使用pivot执行此操作,如下所示:
SELECT OccuredDate, [1], [2], [3], [4]
FROM
(
SELECT OccuredDate, TypeID FROM Table1) AS SourceTable
PIVOT
(
count(TypeID) FOR TypeID IN ([1], [2], [3], [4])
) AS PivotTable
每月版本:
SELECT
DATEADD(month, DATEDIFF(month, 0, OccuredDate), 0) as Month,
sum([1]) as [1],
sum([2]) as [2],
sum([3]) as [3],
sum([4]) as [4]
FROM
(
SELECT OccuredDate, TypeID FROM Table1) AS SourceTable
PIVOT
(
count(TypeID) FOR TypeID IN ([1], [2], [3], [4])
) AS PivotTable
group by
DATEADD(month, DATEDIFF(month, 0, OccuredDate), 0)
编辑:重写每月SQL