如何在sql查询中根据年份计算月份? [英] how to get count of month based on year in sql query?

查看:94
本文介绍了如何在sql查询中根据年份计算月份?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我需要创建一个查询,我将把年份作为int传递,并将获得该年度所有月份的所有记录。



所以例如,如果我输入2013,输出将如下所示

月数
jan 10
feb 0
mar 25
apr 15
may 15
jun 14
7月12
aug 0
sep 22
oct 15
nov 26
dec 0



i尝试下面的查询,这给我输出如下

 jan 10 

b 25
apr 15
may 15
jun 14
7月12

sep 22
oct 15
nov 26



这是我的查询。

 选择月(DepotArrivalDate),count(*)
来自 tbl_CMS_Container
WHERE year(DepotArrivalDate)= ' 2013'
group by 月(DepotArrivalDate)



问题是我没有任何feb / dec月的记录所以这个查询没有给我任何输出的那一行,但我想要那个,如果那样没有它应该显示0像第一个输出。

解决方案

创建一个包含完整月份的表变量,并填充十二个选项。



然后使用左连接获得你想要的东西。



类似于:



< br /> 
声明@Months表(月份varchar(3))< br />
< br />
插入@Months值('Jan'),('Feb'),('Mar'),....< br />
< br />
选择M.Month ,计算(*)< br />
来自@Months M< br />
left join ....< br />


您可能希望创建一个包含您期望的所有月/年/计数组合的表 - 然后使用您的结果更新该表。您可能希望初始化具有零的表的计数字段。



另一个更通用的选项将使用1月 - 12月(1-12)的单个列表然后你可以使用LEFT JOIN来查询你的查询,只匹配月份的数值:一次只能使用一年,但总是很好。



从LEFT-JOIN选项创建返回集,你可以使用ISNULL(你的计数列,0)用0来代替缺少月份的空值



< b> 的

Hi,
i need to create a query where i will pass year as int and will get all the records in all the months of that year.

so for example if i enter 2013 the output will be like below

month  count 
jan     10 
feb     0
mar     25
apr     15
may     15
jun     14
july    12
aug     0
sep     22
oct    15 
nov    26 
dec     0


i tried below query which gives me output like below

jan     10 

mar     25
apr     15
may     15
jun     14
july    12

sep     22
oct    15 
nov    26 


here is my query.

select month(DepotArrivalDate), count(*)
from tbl_CMS_Container
WHERE     year(DepotArrivalDate) = '2013' 
group by month(DepotArrivalDate) 


the issue is i dont have any record for feb / dec month so this query is not giving me any output for that row but i want that if that do not have it should show 0 like first output.

解决方案

Create a table variable with the full set of months, and populate with the twelve options.

Then use left join to get what you want.

Something like:

<br />
declare @Months table ( Month varchar(3))<br />
<br />
insert into @Months values ('Jan'), ('Feb'), ('Mar'), .... <br />
<br />
select M.Month, count(*)<br />
from @Months M<br />
left join ....<br />


You may wish to create a table with all of the month/year/count combos you expect - then update that with your results. You may wish to initialize the count field of the table w/zeros.

Another option, more generalized, would employ a single list of Jan - Dec (1-12) and you may then use a LEFT JOIN to your query, matching only the month's numeric values: good for only one year at a time, but always good.

When creating the return set from the LEFT-JOIN option, you may use ISNULL(your-count-column, 0) to replace the nulls from missing months with 0's


这篇关于如何在sql查询中根据年份计算月份?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆