次を使用すると、データのピボットが解除され、次のコマンドを使用して値が連結されます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 FiddlewithDemoを参照してください。
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 FiddlewithDemoを参照してください。結果は次のとおりです。
| ID | BAD_COLUMNS | BAD_VALUES |
---------------------------------------
| P3 | Price_1, Price_3 | aa, bb |
| P4 | Price_2 | cc |