2012-11-30 206 views
0

海蘭,我有多個值,我需要檢查
列表 例如:
1,2,4,
3,4,應該是:逗號分隔值到多個位列

day1 day2 day3 day4 
_1____1____0____1 
_0____0____1____1 

一種方法是

CAST(CASE WHEN PATINDEX('1,', [day]) > 0 THEN 1 ELSE 0 END AS BIT) as [day1], 
CAST(CASE WHEN PATINDEX('2,', [day]) > 0 THEN 1 ELSE 0 END AS BIT) as [day2], 
CAST(CASE WHEN PATINDEX('3,', [day]) > 0 THEN 1 ELSE 0 END AS BIT) as [day3], 
CAST(CASE WHEN PATINDEX('4,', [day]) > 0 THEN 1 ELSE 0 END AS BIT) as [day4] 

請幫助我一個更好的方法,因爲我有多個列
謝謝

+0

你可以有1,2,4,15000作爲輸入?什麼限制? –

+0

這裏是一篇關於它的文章:http://www.sqlteam.com/article/parsing-csv-values-into-multiple-rows – Chris

+0

@Chris我知道我可以返回一個包含多行的表,但我需要多個'Columns ' – Zyku

回答

1

您可以使用您的選擇與字符串的字符串拆分功能。

declare @T table 
(
    ID int identity, 
    day varchar(20) 
) 

insert into @T values 
('1,2,4,'), 
('3,4,') 

select isnull(P.[1], 0) as day1, 
     isnull(P.[2], 0) as day2, 
     isnull(P.[3], 0) as day3, 
     isnull(P.[4], 0) as day4 
from 
    (
    select T.ID, S.s, 1 as x 
    from @T as T 
    cross apply dbo.Split(',', T.day) as S 
) as T 
pivot (min(T.x) for T.s in ([1],[2],[3],[4])) as p 

結果:

day1 day2 day3 day4 
1  1  0  1 
0  0  1  1 
0

您可以使用概述的分割函數here,然後將這些值轉換爲列。

或!

This答案看起來像你想要做的一樣的事情。

0

使用第二個表來存儲有效日期,然後在其上查詢。看到這個fiddle

編輯 查看更新後fiddle,或下面的代碼:

create table test (day1 varchar(8), day2 varchar(8), day3 varchar(8), day4 varchar(8)); 
insert into test (day1, day2, day3, day4) values ('day1', 'day2', 'day3', 'day4'); 

create table valid_days (valid_day_no int); 
insert into valid_days values (1), (2), (4); 

select cast (case when exists(select 1 from valid_days where valid_day_no = substring(day1, 4, len(day1))) then 1 else 0 end as bit) day1, 
     cast (case when exists(select 1 from valid_days where valid_day_no = substring(day2, 4, len(day2))) then 1 else 0 end as bit) day2, 
     cast (case when exists(select 1 from valid_days where valid_day_no = substring(day3, 4, len(day3))) then 1 else 0 end as bit) day3, 
     cast (case when exists(select 1 from valid_days where valid_day_no = substring(day1, 4, len(day4))) then 1 else 0 end as bit) day4 
from test; 

注意,SQL是一個固定的列的語言,你需要使用一種編程語言動態生成可變長度列的查詢。

+0

('day1'),('day2'),('day3'),('day4');這些應該是'COLUMNS' – Zyku

+0

更新了答案。 – Isaac