每个月我们都会使用小部件。我们构建红色,绿色和蓝色小部件。 如何编写一个查询,按月计算每种颜色生成的小部件数量?我希望结果是一个图表,y轴标记为红色,绿色,蓝色,x轴标记为Jan,Feb,Mar等。
年份数无关紧要,我希望查询结果如下所示。生成窗口小部件的日期是可用数据的一部分(ex 04/02/2016)。我希望我可以使用datepart拉月,但我希望它分组成列而不是行。请帮帮忙?
答案 0 :(得分:1)
使用此代码:
IF OBJECT_ID('tempdb..#UsingColor','U') IS NOT NULL DROP TABLE #UsingColor;
CREATE TABLE #UsingColor
(color VARCHAR(10) NOT NULL
, usingDate DATE NOT NULL)
INSERT INTO #UsingColor(color, usingDate)
VALUES('red', '20160101')
, ('green', '20160101')
, ('blue', '20160201')
, ('red','20160201')
, ('red', '20160301')
, ('green', '20160301')
, ('blue', '20160301')
, ('orange','20160301')
, ('green', '20160401')
, ('green', '20160401')
, ('blue', '20160401')
, ('orange','20160401')
, ('blue', '20160401')
, ('green', '20160401')
, ('white', '20160401')
, ('orange','20160401')
, ('green', '20160501')
, ('white', '20160501')
, ('orange','20160601')
, ('white', '20160601')
, ('orange','20160601')
, ('green', '20160701')
, ('blue', '20160701')
, ('red','20160701')
, ('red', '20160801')
, ('green', '20160801')
, ('blue', '20160801')
, ('orange','20160801')
, ('green', '20160901')
, ('green', '20160901')
, ('blue', '20160901')
, ('orange','20160901')
, ('blue', '20160901')
, ('green', '20160901')
, ('white', '20160901')
, ('orange','20160901')
, ('green', '20161001')
, ('white', '20161001')
, ('orange','20161101')
, ('white', '20161101')
, ('orange','20161101')
--, ('black', '20161201')
SELECT color
, [1] AS Jan
, [2] AS Feb
, [3] AS Mar
, [4] AS Apr
, [5] AS May
, [6] AS Jun
, [7] AS Jul
, [8] AS Aug
, [9] AS Sep
, [10] AS Oct
, [11] AS Nov
, [12] AS Dec
FROM(
SELECT color, 1 AS cntr, MONTH(usingDate) AS m FROM #UsingColor) AS D
PIVOT(COUNT(cntr) FOR m IN([1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12])) AS P