可以这样写的另一种方式是:
SELECT id,
case col
when 'DoNotEmail' then 'DNE'
when 'DoNotMail' then 'DNM'
when 'DoNotPhone' then 'DNP'
when 'DoNotSMS' then 'DNS'
end Suppressions
FROM
(
SELECT t.ID,
s.col,
CASE s.col
WHEN 'DoNotEmail' THEN DoNotEmail
WHEN 'DoNotMail' THEN DoNotMail
WHEN 'DoNotPhone' THEN DoNotPhone
WHEN 'DoNotSMS' THEN DoNotSMS
END AS DATA
FROM Transactions t
CROSS JOIN
(
SELECT 'DoNotEmail' AS col
UNION ALL SELECT 'DoNotMail'
UNION ALL SELECT 'DoNotPhone'
UNION ALL SELECT 'DoNotSMS'
) s
) s
where data = 'true';
请参阅SQL Fiddle with Demo。
由于您使用的是 SQL Server,因此您可以实现该UNPIVOT
功能:
select id,
case col
when 'DoNotEmail' then 'DNE'
when 'DoNotMail' then 'DNM'
when 'DoNotPhone' then 'DNP'
when 'DoNotSMS' then 'DNS'
end Suppressions
from Transactions
unpivot
(
value
for col in ([DoNotEmail], [DoNotMail], [DoNotPhone], [DoNotSMS])
) piv
where value = 'true'
请参阅带有演示的 SQL Fiddle