列明:id(主键自增) 0(bool) 1(bool) 2(bool) 3(bool)
1 1 0 0 0
2 0 1 1 1
查询结果为: 如果列为1,则增加一行,值为主键+'_'+当前为1的那个列名,试例和下面那样
1_0
2_1
2_2
2_3
跪求大侠指点
------解决方案--------------------
if OBJECT_ID('tempdb..#temp', 'u') is not null drop table #temp;
go
create table #temp( [id] int, [0] bit, [1] bit, [2] bit, [3] bit);
insert #temp
select '1','1','0','0','0' union all
select '2','0','1','1','1'
--SQL:
select
result=LTRIM(id)+'_'+colname
from #temp a
UNPIVOT
(value FOR colname IN([0],[1],[2],[3])) b --列名不固定,用动态SQL拼即可
WHERE value = 1
/*
result
1_0
2_1
2_2
2_3
*/
------解决方案--------------------
--如果是sql 2000
create table #tb(id int,[0(bool)] bit,[1(bool)] bit,[2(bool)] bit,[3(bool)] bit)
insert into #tb
select 1,1,0,0,0
union all select 2,0,1,1,1
select aid=identity(int,1,1), id,col
into #tc
from (
select id,[0(bool)] as col from #tb where [0(bool)]=1