我想知道是否有更有效的方式从一年中的每个月获得计数,而不是我现在的方式。目前我正在使用单个select语句来计算Jan,Mar等的计数,然后将它们全部加入到单个select语句中。
Select distinct
count(item1 + item2) as 'Count of Items',
month(sub_date) as 'month'
from table1
where month(sub_date)='1'
and year(sub_date)='2012'
我会在第1-12个月重复一遍,然后加入12 select语句来获得这样的表格
jan feb mar apr may jun july aug sept oct nov dec
1 2 2 1 3 5 5 2 6 7 2 1
任何有关如何重做我的查询的信息都将不胜感激。
答案 0 :(得分:3)
您应该可以在GROUP BY
和month(sub_date)
上使用year(sub_date)
:
Select
count(item1 + item2) as 'Count of Items',
month(sub_date) as 'month',
year(sub_date) as year
from table1
group by month(sub_date), year(sub_date)
此结果将在多行中。 GROUP BY
和month
year
允许您返回多年,如果您只想返回2012年,那么您可以包含与此类似的原始WHERE year(sub_date) =2012
子句:
Select
count(item1 + item2) as 'Count of Items',
month(sub_date) as 'month'
from table1
where year(sub_date) = 2012
group by month(sub_date)
然后,如果您希望每年将数据放在一行中,则可以应用 pivot 函数。
select *
from
(
Select item1 + item2 Items,
month(sub_date) as 'month'
from table1
where year(sub_date) =2012
) src
pivot
(
sum(Items)
for month in ([1], [2])
) piv
见SQL Fiddle with Demo。 PIVOT
函数将数据从行转换为列。
答案 1 :(得分:0)
GROUP BY
就是您想要的:http://msdn.microsoft.com/en-us/library/ms177673.aspx
SELECT MONTH(sub_date) AS [month],
COUNT(item1 + item2) AS [Count of Items]
FROM table1
WHERE YEAR(sub_date) = 2012
GROUP BY MONTH(sub_date)
我假设,正如我从你的帖子中推测的那样,你只想要12行,每一个月给定一年(在这种情况下,2012年)。如果您想要包括所有年份,那么您可以将其添加到GROUP BY
子句中,如下所示:
GROUP BY YEAR(sub_date), MONTH(sub_date)