3

我想创建一个表格,该表格将按月显示本年度的每周日计数,如下表所示。

我知道我需要使用 with 语句,但还没有设法破解它。

我正在使用 MS SQL Server 2008 r2 并且我也是 SQL 的初级所以任何帮助将不胜感激

预期输出:

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
4

1 回答 1

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)
于 2013-09-17T11:32:54.410 回答