我有一张名为“Days”的桌子
Day 1 Day 2 Day 3 Day 4 Day 5 Day 6 Day 7
1 1 1 1 0 0 0
1 1 1 1 0 0 0
具有相应的细节。其中1为'true'且0为false。
DaY 1 - sunday
day 2- monday
day 3 - tuesday
day 4- wednesday
day5 - thursday
day 6 - friday
dayy 7- saturday
1 - denotes there is work on the given day
0 - denotes there is no work on the given day.
鉴于上述细节,我需要进行列到表的映射 并且需要生成一个这样的表,我需要只获取具有标志1
的数据1 Sunday
2 Monday
3 Tuesday
4 Wednesday
第一张唱片。
答案 0 :(得分:4)
WITH [days] (id, day1, day2, day3, day4, day5, day6, day7) AS
(
SELECT 1, 1, 1, 1, 1, 1, 0, 0
UNION ALL
SELECT 2, 1, 1, 1, 1, 1, 0, 0
)
SELECT id, DATENAME(dw, DATEADD(d, CAST(SUBSTRING(wd, 4, 1) AS INT), '2005-01-01')), work
FROM [days]
UNPIVOT
(
work FOR wd IN
(day1, day2, day3, day4, day5, day6, day7)
) AS up
WHERE work = 1
答案 1 :(得分:2)
我相信你正在寻找以下内容:
select
case when day1=1 then '1 Sunday' end Sunday,
case when day2=1 then '2 Monday' end Monday,
case when day3=1 then '3 Tuesday' end Tuesday,
case when day4=1 then '4 Wednesday' end Wednesday,
case when day5=1 then '5 Thursday' end Thursday,
case when day6=1 then '6 Friday' end Friday,
case when day7=1 then '7 Saturday' end Saturday
from [table]
where day1+day2+day3+day4+day5+day6+day7 <> 7
那些应该是行?然后,您需要首先unpivot
源数据:
select
cast(substring(dayname, 4, 1) as tinyint) as DayNumber,
case cast(substring(dayname, 4, 1) as tinyint)
when 1 then 'Sunday'
when 2 then 'Monday'
when 3 then 'Tuesday'
when 4 then 'Wednesday'
when 5 then 'Thursday'
when 6 then 'Friday'
when 7 then 'Saturday' end [DayName]
, DayFlag
from (select * from [table] t where day1+day2+day3+day4+day5+day6+day7 <> 7) f
unpivot
(
DayFlag for DayName in ([day1], [day2], [day3], [day4], [day5], [day6], [day7])
) unpvt
where DayFlag = 1 --is this what you need?
答案 2 :(得分:2)
免责声明 - 我知道它并不能解决您的问题,但是如果将表格反规格化为以下内容并不是更好:
ID | WeekNo | DayNo
----------------------
1 1 1
2 1 2
3 1 3
4 2 6
5 2 7
因此,您实际上只会在当天进行工作的表格中添加天数(即第1周的第4-7天没有工作,第2周仅在第6天和第7天进行工作)。 ??然后你可以在你的.net应用程序中找到一些逻辑,这些逻辑“知道”本周完整的日期,并向你提供了一个例外列表(即任何给定的WeekNo表中没有的日期)
这将是我对这场'辩论'的第一个选择......