简体   繁体   中英

SQL Select Column Titles Where Column Value Equals Yes

I have some legacy software that has an extremely archaic way of displaying data within SQL.

Basically I have a data input screen with a label and a yes/no box for each one, this in SQL ends up with a column representing the field and then the resultant value being the answer to this yes no box.

My Example

B@ | PolRef@ | HH01 | HH02 | HH03 | HH04 
0  | LYJX01  |  Yes |  No  |  No  | Yes
0  | POMS01  |  No |  No  |  No  | Yes

This goes on for roughly 72 yes/no boxes.

I basically require the name of of the column return for that 'PolRef@' if the value on that row equals 'Yes'.

I started writing the following

SELECT hqe1.B@ , hqe1.PolRef@ , CASE WHEN hqe1.Hh01 = 'Yes' THEN 'HH01' END AS [Endorsement] FROM dbo.ic_BD_HQE1 hqe1
WHERE CASE WHEN hqe1.Hh01 = 'Yes' THEN 'HH01' END IS NOT NULL
UNION
SELECT hqe1.B@ , hqe1.PolRef@ , CASE WHEN hqe1.Hh02 = 'Yes' THEN 'HH02' END AS [Endorsement] FROM dbo.ic_BD_HQE1 hqe1
WHERE CASE WHEN hqe1.Hh02 = 'Yes' THEN 'HH02' END IS NOT NULL
ORDER BY hqe1.PolRef@

But surely there has to be a quicker way?

Can anyone help at all?

You can use unpivot to do this.

select B@ , PolRef@, endorsement
from
(select * from hqe1) t
unpivot
(col for endorsement in (HH01,HH02,HH03,HH04)) u
where col = 'Yes'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM