Dav*_*nes 1 sql-server select unpivot
我有一个名为'transactions'的数据库表,有多个列.对于每个事务行,我需要从指定列表生成每列一行的导出
交易表
ID, DoNotEmail, DoNotMail, DoNotPhone, DoNotSMS 1000, true, false, true, true
以下规则需要适用.
设置DoNotEmail然后输出'DNE'
设置DoNotMail然后输出'DNM'
设置DoNotPhone然后输出'DNP'
设置DoNotSMS然后输出'DNS'
出口需要看起来像:
ID, Suppressions 1000, DNE 1000, DNP 1000, DNS
我真的很困惑,我能让它工作的唯一方法是将每个列的insert语句分成两个临时表非常可怕.Urgh.
这可能吗?
谢谢你的帮助.
达伦
抱歉格式化.
如果您只有四列,这可能会有效:
SELECT id,
'DNE' AS Suppressions
FROM transactions
WHERE donotemail = 'true'
UNION ALL
SELECT id,
'DNM' AS Suppressions
FROM transactions
WHERE donotmail = 'true'
UNION ALL
SELECT id,
'DNP' AS Suppressions
FROM transactions
WHERE donotphone = 'true'
UNION ALL
SELECT id,
'DNS' AS Suppressions
FROM transactions
WHERE donotsms = 'true'
Run Code Online (Sandbox Code Playgroud)
另一种可以编写的方法是:
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';
Run Code Online (Sandbox Code Playgroud)
由于您使用的是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'
Run Code Online (Sandbox Code Playgroud)