您可以使用以下内容对数据进行反透视,然后使用以下方法连接值FOR XML PATH
:
;with cte as
(
select id, col, data
from
(
select t.id,
c.col,
case c.col
when 'Price_1' then Price_1
when 'Price_2' then Price_2
when 'Price_3' then Price_3
end as data
from yourtable t
cross join
(
select 'Price_1' as col
union all select 'Price_2'
union all select 'Price_3'
) c
) src
where isnumeric(data) = 0
)
select distinct c1.id,
stuff((select ', ' + col
from cte c2
where c1.id = c2.id
FOR XML PATH (''))
, 1, 1, '') AS Bad_columns,
stuff((select ', ' + data
from cte c2
where c1.id = c2.id
FOR XML PATH (''))
, 1, 1, '') AS Bad_Values
from cte c1
请参阅SQL Fiddle with Demo。
这也可以使用以下unpivot
函数编写:
;with cte as
(
select id, col, data
from yourtable
unpivot
(
data
for col in ([Price_1], [Price_2], [Price_3])
) unpiv
where isnumeric(data) = 0
)
select distinct c1.id,
stuff((select ', ' + col
from cte c2
where c1.id = c2.id
FOR XML PATH (''))
, 1, 1, '') AS Bad_columns,
stuff((select ', ' + data
from cte c2
where c1.id = c2.id
FOR XML PATH (''))
, 1, 1, '') AS Bad_Values
from cte c1
请参阅SQL Fiddle with Demo。结果是:
| ID | BAD_COLUMNS | BAD_VALUES |
---------------------------------------
| P3 | Price_1, Price_3 | aa, bb |
| P4 | Price_2 | cc |