2010-09-15 207 views
2

我有這樣一個名爲「天」SQL腳本幫助

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爲'真'且0爲假。

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 

爲第一條記錄。

+2

爲什麼'5星期四'? – 2010-09-15 11:44:38

+0

什麼是你的表的主鍵? – 2010-09-15 11:46:56

+0

該表有Id,這是主鍵,不在表 – SRA 2010-09-15 12:12:05

回答

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? 
+0

嗨dennis謝謝你。我怎樣才能在一個單獨的列中獲得日數? – SRA 2010-09-15 13:16:32

+0

@Sunil Ramu,'cast(substring(dayname,4,1)as tinyint)' – 2010-09-15 13:37:40

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 
2

免責聲明 - 我知道這並不解決您的問題,但它不會是最好有一個已被取消的表-normalized出來是這樣的:

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而言,這些天不在表中)

這將是我對這場「辯論」的第一個備選想法......

+0

同意,結構是錯誤的,需要在做任何事之前先修復。 – HLGEM 2010-09-15 13:44:55

+0

@HLGEM我不知道。正常化在這裏真的有必要嗎?我越想越多,我越不喜歡意大利麪條表。把它想成面具。我會在那裏放置一個varchar(7)面具,並完成它,但如果它需要索引然後雅,這是好的,因爲它是。 – 2010-09-15 13:45:23