我想创建一个表格,它会显示当月的每周工作日数,如下表所示。
我知道我需要使用with语句但尚未设法破解它。
我正在使用MS SQL Server 2008 r2,我也是SQL的Junior,所以任何帮助都将不胜感激
预计输出:
Month Mon Tue Wed Thu Fri Sat Sun Sum
-------------------------------------------
January 4 5 5 5 4 4 4 31
February 4 4 4 4 4 4 4 28
March 4 4 4 4 5 5 5 31
April 5 5 4 4 4 4 4 30
May 4 4 5 5 5 4 4 31
June 4 4 4 4 4 5 5 30
July 5 5 5 4 4 4 4 31
August 4 4 4 5 5 5 4 31
September 5 4 4 4 4 4 5 30
October 4 5 5 5 4 4 4 31
November 4 4 4 4 5 5 4 30
December 5 5 4 4 4 4 5 31
答案 0 :(得分:6)
-- count weekdays in a year
declare @y int = 2013
declare @d datetime = dateadd(year, @y - 1900, 0)
;with cte
as
(
select 1 a,
left(datename(weekday, @d), 3) b,
datename(month, 0) Month,
1 sort
union all
select a + 1 a,
left(datename(weekday, @d + a), 3) b,
datename(month, @d + a) Month,
datepart(month, @d + a) sort
from cte where a < datepart(dayofyear, dateadd(year, 1, @d)-1)
)
select month, [Mon],[Tue],[Wed],[Thu],[Fri],[Sat],[Sun],
[Mon]+[Tue]+[Wed]+[Thu]+[Fri]+[Sat]+[Sun] [Sum]
from cte
pivot (count(a) FOR [b] IN ([Mon],[Tue],[Wed],[Thu],[Fri],[Sat],[Sun],[Sum])) AS pvt
order by sort
option (maxrecursion 366)