逗号分隔值到多个BIT列

时间:2012-11-30 14:07:31

标签: sql-server-2008 tsql

Hy,我有多个值,我需要一张支票清单
例如:
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]  

请帮我一个更好的方法,因为我有多个列
感谢

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您可以使用概述here的拆分功能,然后将值转换为列。

OR!

This回答看起来就像你想做的那样。

答案 2 :(得分: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是一种固定的列语言,您需要使用编程语言来动态构建可变长度的列查询。