将Excel公式转换为SQL

时间:2013-02-28 09:19:06

标签: sql excel tsql

我在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

由于

韦恩

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

如果您使用的是sql-server 2005或更高版本,则这是一种使用CTE的方法。这是 demo

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