云服务器网:购买云服务器和VPS必上的网站!

大于等于28SQL Server中超过28天的月份统计

There are occasions when one may want to calculate months with more than 28 days in SQL Server. The challenge that may arise is th

There are occasions when one may want to calculate months with more than 28 days in SQL Server. The challenge that may arise is that a generic T-SQL function does not exist for this computation. Nonetheless, the ability to perform such computation is made possible through the proper use of date functions in T-SQL, combined with the ability to leverage cursors or a looping construct within a stored procedure.

In this post, we shall be focusing on how to count the number of months in SQL Server with a duration of more than 28 days. We shall start by creating a cursor to loop through each year and month, and then use a combination of several date functions to achieve the desired outcome.

首先,我们创建一个游标来循环每年和每个月:

— Declare Cursor declare c1 cursor for select distinct year(date) as [year], month(date) as [month] from tablename order by [year], [month]

接下来,我们使用dateadd函数来计算每月的总天数:

declare @days int, @month date set @month = dateadd(mm, 1, datefromparts(@year, @month, 1)) set @days = datediff(dd, datefromparts(@year, @month, 1), @month)

随后,我们通过比较总天数会不会大于28来判断每月会不会包括天数大于28天:

if @days > 28 begin — Increment the count set @longmonthcount = @longmonthcount + 1 end

最后,我们返回结果:

— Return result select @longmonthcount count

因此,以上代码是怎么用游标和dateadd函数统计超过28天的月份。这类方法可以确保实现这类统计。

本文来源:https://www.yuntue.com/post/110770.html | 云服务器网,转载请注明出处!

关于作者: yuntue

云服务器(www.yuntue.com)是一家专门做阿里云服务器代金券、腾讯云服务器优惠券的网站,这里你可以找到阿里云服务器腾讯云服务器等国内主流云服务器优惠价格,以及海外云服务器、vps主机等优惠信息,我们会为你提供性价比最高的云服务器和域名、数据库、CDN、免费邮箱等企业常用互联网资源。

为您推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注