转置 table 并按列转储

Transpose table and dump it by columns

我有一个关注table:

id code bool1 bool2 bool3 bool4
1  A    true  true  false true
2  B    false true  true  true

有没有可能得到这样的东西?

id code bool
1  A    name_for_bool1  // name of column bool1 e.g. 'worker'
1  A    name_for_bool2
1  A    name_for_bool4
2  A    name_for_bool2
2  A    name_for_bool3
2  A    name_for_bool4

我想告诉你我试过的方法,但完全错了 - 我不知道该怎么做..

检查这个... Unpivot

declare @t table(id int, code varchar(50), bool1 varchar(50),bool2 varchar(50),bool3 varchar(50),bool4 varchar(50))
insert into @t values (1,'A','true','true','false','true')
,(2,'B','false','true','true','true')

select * from @t

select id, code , boolvalue
from 
@t
unpivot
(
  boolvalue
  for boolvalue1 in (bool1, bool2,bool3,bool4)

) u;

这个怎么样:

SELECT id, code, 'name_for_bool1' bool FROM src WHERE bool1
UNION ALL
SELECT id, code, 'name_for_bool2' bool FROM src WHERE bool2
UNION ALL
SELECT id, code, 'name_for_bool3' bool FROM src WHERE bool3
UNION ALL
SELECT id, code, 'name_for_bool4' bool FROM src WHERE bool4