SQL Group按月加入

时间:2014-04-12 20:08:01

标签: sql date

我有3个不同的查询,需要找到一种在单个gridview中显示结果的方法,但这种方式是创建3个不同的网格。 我的代码是这样的,并试图找到一种方法来加入一个显示月份和列的行显示“笔记本电脑”,“个人电脑”和“总计”的行。

SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, activation_date), 0) AS MyMonth, COUNT(stb_group) AS Laptop 
FROM inventary 
WHERE (activation_date > '10-01-2013') AND (stb_group = 'Laptop') 
GROUP BY DATEADD(MONTH, DATEDIFF(MONTH, 0, activation_date), 0)


SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, activation_date), 0) AS MyMonth, COUNT(stb_group) AS PC 
FROM inventary 
WHERE (activation_date > '10-01-2013') AND (stb_group = 'PC') 
GROUP BY DATEADD(MONTH, DATEDIFF(MONTH, 0, activation_date), 0)


SELECT     DATEADD(MONTH, DATEDIFF(MONTH, 0, activation_date), 0) AS MyMonth, COUNT(stb_group) AS Units
FROM         inventary
WHERE     (activation_date > '10-01-2013')
GROUP BY DATEADD(MONTH, DATEDIFF(MONTH, 0, activation_date), 0)

1 个答案:

答案 0 :(得分:0)

试试这个

SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, activation_date), 0) AS MyMonth, 
COUNT(case when stb_group = 'Laptop' then stb_group end) AS Laptop,
COUNT(case when stb_group = 'PC' then stb_group end) AS PC, 
COUNT(stb_group) AS Units
FROM inventary 
WHERE (activation_date > '10-01-2013')  
GROUP BY DATEADD(MONTH, DATEDIFF(MONTH, 0, activation_date), 0)