按月份和类型统计记录

Count records by month & type

我在 SQL Server 2014 中有一个 table 具有以下架构:

OccuredDate (date)     TypeID (int)
2014-1-1               1
2014-1-2               1
2014-2-5               4
2015-5-23              2
2015-6-3               3

…它有数千行由日期和类型 ID 组成,跨越数年。

所以我可以将其绘制到图表组件中,我正在尝试构建一个查询,对于给定的年份 1) returns 每个 - 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 魔法可以做到这一点吗?

谢谢!

您可以使用 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 Fiddle 中进行测试:daily and monthly

编辑:重写每月 SQL