我有一张表Holiday_Details
下表中的列
CALENDAR_DATE, Day1,Day2,Day3,Day4,Day5,Day6,Day7,Day8,Day9,Day10,Day11,Day12,Day13, Day14,Day15,Day16,Day17,Day18,Day19,Day20,Day21,Day22,Day23,Day24,Day25,Day26,Day27, Day28,Day29,Day30,Day31 the columns from Day1 to Day31 are having null values.
Year Month Days
2014 1 01-01-2014
2014 1 02-02-2014
2014 1 03-03-2014
2014 1 04-03-2014
2014 1 05-03-2014
现在我想要的结果如下:
结果
Year Month Day1 Day2 Day3 Day4 Day5 Day6 Day31
2014 1 1 1 1 0 0 ……. 1
2014 2 0 0 1 0 0 ……. 1
2014 3 0 0 1 0 0 ……. 1
工作日= 1 (周一,周二,周三,周四,周五)
假日= 0(周六,周日)
请告诉我如何将列CALENDAR_DATES转换为与每个月和每年相对应的行。请帮助我,因为我无法获得如上所示的此订单。
答案 0 :(得分:1)
测试表:
create table dates(Year int, Month int, Days int, date date)
;with cte as
(
select 0 x
union all
select x + 1
from cte
where x < 364
)
insert dates
select 2014, month(dateadd(d, x, '20140101')), day(dateadd(d, x, '20140101')), dateadd(d, x, '20140101')
from cte
option (maxrecursion 0)
查询:
select *
from
(
select year, month, days, case when datediff(d, 0, date)%7 in (5,6)
then 0 else 1 end status
from dates
) x
pivot (max(status) for Days in (
[1], [2], [3], [4], [5], [6], [7], [8], [9],[10],
[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],
[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31]
)) as pvt
答案 1 :(得分:0)
试试这个:
;with CalendarDate as
(
Select 1 as Level , convert(date,'20140101') as myDate
union all
Select Level +1 , dateadd(day,1,myDate) from CalendarDate
where Level<100
)
Select Year,Month,
[Day1],[Day2],[Day3],[Day4],[Day5],[Day6],[Day7],[Day8],[Day9],[Day10],[Day11],[Day12], [Day13],[Day14],[Day15],[Day16],[Day17],[Day18],[Day19],[Day20],[Day21],[Day22],[Day23], [Day24],[Day25],[Day26],[Day27],[Day28],[Day29],[Day30],[Day31]
from
(
Select myDate,
year(myDate) as Year,
Month(myDate) as Month,
case when datename(Weekday,myDate) in ('Saturday','Sunday')
then 'Weekend'
ELSE
'Day'+convert(varchar(3),day(myDate))
END as Col1
from CalendarDate
) pv
pivot
(
count(myDate)
for Col1 in
([Day1],[Day2],[Day3],[Day4],[Day5],[Day6],[Day7],[Day8],[Day9],[Day10],[Day11],[Day12],[Day13],[Day14],[Day15],[Day16],[Day17],[Day18],[Day19],[Day20],[Day21],[Day22],[Day23],[Day24],[Day25],[Day26],[Day27],[Day28],[Day29],[Day30],[Day31]
)
)
pvt
结果: - SQL Fiddle