2013-03-25 41 views
1

我想知道是否有一个更有效的方法来从一年中的每个月获得一个计数,除非我现在正在做的方式。目前,我使用单个select语句从1月,3月等计算,然后将它们全部加入到单个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 

上如何去重做我的查询将任何信息赞赏。

回答

3

您应该能够使用上都month(sub_date)year(sub_date)一个GROUP BY

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两个monthyear将允许您返回多个年,如果你只想返回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) 

然后,如果你想在一个数据每年单排,那么你可以申请支点函数。

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 DemoPIVOT函数将数据从行转换为列。

+1

的OP只希望它为一年,如可以在选择列表中可以看出。另外,GROUP BY不使用AND分隔字段。 – siride 2013-03-25 15:02:06

+0

@siride我意识到这一点,我展示了如何在'month'和'year'上使用'GROUP BY'来实现这一点。 – Taryn 2013-03-25 15:08:30

+0

这看起来很正确,我会仔细研究它是否确实我想要的是。谢谢! – user2146212 2013-03-25 15:15:05

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) 
+0

我希望每个月都有一个列,这就是为什么我目前正在加入每个月的单个select语句。 – user2146212 2013-03-25 15:09:35

相关问题