0

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]  

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

4

3 回答 3

1

您可以将您选择的字符串拆分功能与 pivot 一起使用。

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
于 2012-11-30T15:06:23.733 回答
0

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

或者!

这个答案看起来和你想做的一样。

于 2012-11-30T14:17:24.923 回答
0

使用第二个表存储有效日期,然后对其进行查询。看到这个小提琴

编辑 见更新的小提琴,或下面的代码:

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

于 2012-11-30T14:21:10.420 回答