一种可能的解决方案是动态 sql 取消透视数据并进一步连接:
declare @stmt nvarchar(max)
select @stmt = IsNull(@stmt + ', ', '') + quotename(name)
from sys.columns
where object_id = object_id('TableName') and name != 'ID'
order by column_id
set @stmt = ';with du as (
select *
from TableName d
unpivot (Val for Name in (' + @stmt + ')) u
)
select d.ID, IsNull(left(Cols, len(Cols) - 1), ''<None>'') as ColumnsSet
from (select ID from TableName) d
cross apply (select (select Name + '', ''
from du
where Val = 1 and ID = d.ID
for xml path ('''')) as Cols) c'
print @stmt
exec(@stmt)
对于像这样的数据:
create table TableName (ID int, Col1 bit, Col2 bit, Col3 bit)
insert into TableName values
(1, 0, 1, 1)
,(2, 1, 1, 1)
,(3, 1, 0, 0)
,(4, 0, 0, 0)
输出是:
ID ColumnsSet
----------- -----------------
1 Col2, Col3
2 Col1, Col2, Col3
3 Col1
4 <None>