当前位置: 代码迷 >> Sql Server >> 求一SQL语句,查询不确定列中为真的记录,该怎么解决
  详细解决方案

求一SQL语句,查询不确定列中为真的记录,该怎么解决

热度:15   发布时间:2016-04-27 13:27:07.0
求一SQL语句,查询不确定列中为真的记录
一个表 T1有中有N列,分别为从A1到A10,数值为BOOL型,每条记录中不确定列为真,其他列都为假,怎么查询出其中为真的记录?

------解决方案--------------------
SQL code
if object_id('test1') is not null    drop table test1;gocreate 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 allselect 1, 0, 1, 1, 1, 0, 0, 0, 0, 0 union allselect 0, 0, 0, 1, 0, 1, 0, 0, 1, 1;goselect 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,A92           A1,A3,A4,A53           A4,A6,A9,A10*/
  相关解决方案