2

我在 Excel 中有一个公式可以计算两个日期之间有多少个星期天,但我想在 SQL 中做同样的事情,但不知道该怎么做。你能帮我吗?

=SUM(INT((WEEKDAY(A1-8,1)+B1-A1)/7))

Declare @From as Datetime 
Declare @To as Datetime 

Set @From = '7 Jan 2013' 
Set @To = '18 Mar 2013' 

SELECT SUM(WEEKDATE(@From-8,1)+ @End-@From)/7)) AS No_Of_Sundays 
FROM TIME

谢谢

韦恩

4

2 回答 2

2

试试这个:

SELECT SUM((CASE WHEN DATEPART(dw, @From) = 7 THEN 1 ELSE 0 END) + DATEDIFF(dd, @From, @To) / 7) AS No_Of_Sundays 

如您所见,这取决于本地化 -> 在俄罗斯,星期日是第 7 天,所以我们检查第一天是否是星期日

这是另一个解决方案:

Declare @From as Datetime 
Declare @To as Datetime 
Declare @sundays as INT

Set @From = '1/02/2013' 
Set @To = '28/02/2013' 
Set @sundays = 0

WHILE (@From <= @To)
BEGIN
    SET @sundays = @sundays + (CASE WHEN DATEPART(dw, @From) = 7 THEN 1 ELSE 0 END)
    SET @From = DATEADD(dd, 1, @From)
END

SELECT @sundays
于 2013-02-28T09:40:05.763 回答
0

如果您使用的是 sql-server 2005 或更高版本,这是一种使用CTE. 这是一个演示

declare @From date = '20130107' --'7 Jan 2013' 
declare @To date = '20130318'  --'18 Mar 2013' 

;with CTE as (
  select 0 number , datename(weekday, @from) dName
  union all
  select number+1, datename(weekday,dateadd(day,number+1,@from)) dName
  from CTE 
  where dateadd(day, number + 1,@from) <= @to and
       datename(weekday,dateadd(day,number,@from)) <> 'sunday'
)

select top(1) (datediff(day,@from,@to) - number )/7 + 
               case when number = 0 and dname <> 'sunday' then 0 else 1 end
               sundays
from CTE
order by number desc
于 2013-02-28T10:36:42.977 回答