日期:2014-05-18  浏览次数:20354 次

求一SQL语句,查询不确定列中为真的记录
一个表 T1有中有N列,分别为从A1到A10,数值为BOOL型,每条记录中不确定列为真,其他列都为假,怎么查询出其中为真的记录?

------解决方案--------------------
SQL code

if object_id('test1') is not null
    drop table test1;
go

create table test1
(
    ID int not null identity(1, 1) primary key,
    A1 bit not null,
    A2 bit not null,
    A3 bit not null,
    A4 bit not null,
    A5 bit not null,
    A6 bit not null,
    A7 bit not null,
    A8 bit not null,
    A9 bit not null,
    A10 bit not null,
);

insert into test1(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10)
select 1, 1, 1, 0, 1, 0, 0, 0, 1, 0 union all
select 1, 0, 1, 1, 1, 0, 0, 0, 0, 0 union all
select 0, 0, 0, 1, 0, 1, 0, 0, 1, 1;
go

select ID, substring(
            (case when A1=1 then ',A1' else '' end) +
            (case when A2=1 then ',A2' else '' end) +
            (case when A3=1 then ',A3' else '' end) +
            (case when A4=1 then ',A4' else '' end) +
            (case when A5=1 then ',A5' else '' end) +
            (case when A6=1 then ',A6' else '' end) +
            (case when A7=1 then ',A7' else '' end) +
            (case when A8=1 then ',A8' else '' end) +
            (case when A9=1 then ',A9' else '' end) +
            (case when A10=1 then ',A10' else '' end), 2, 8000)
from test1;
/*
ID          
----------- -------------------------------
1           A1,A2,A3,A5,A9
2           A1,A3,A4,A5
3           A4,A6,A9,A10
*/