您可以使用UNPIVOT
,CROSS APPLY
并FOR XML PATH
获得结果:
;with cte as
(
select [Job Batch id], [Company Outlet Id],
col, value
from yourtable
unpivot
(
value
for col in ([Clearance required], [Hanky required])
) unpiv
)
select distinct t1.[Job Batch id],
t1.[Company Outlet Id],
left(s.reason, len(s.reason)-1) reason
from cte t1
cross apply
(
select t2.col + ', '
FROM cte t2
where t1.[Job Batch id] = t2.[Job Batch id]
and t1.[Company Outlet Id] = t2.[Company Outlet Id]
FOR XML PATH('')
) s (reason)
请参阅带有演示的 SQL Fiddle
或者您可以使用UNPIVOT
,STUFF
和FOR XML PATH
:
;with cte as
(
select [Job Batch id], [Company Outlet Id],
col, value
from yourtable
unpivot
(
value
for col in ([Clearance required], [Hanky required])
) unpiv
)
select distinct t1.[Job Batch id],
t1.[Company Outlet Id],
STUFF(
(SELECT ', ' + col
FROM cte t2
where t1.[Job Batch id] = t2.[Job Batch id]
and t1.[Company Outlet Id] = t2.[Company Outlet Id]
FOR XML PATH (''))
, 1, 1, '') AS Reason
from cte t1
请参阅带有演示的 SQL Fiddle