简体   繁体   中英

Converting one to many to one to one table in SQL

I need some SQL guidance. I have a table (A) that looks like this (note the rows should be unique by ID+CommType):

Member ID CommType Consent Emailable
1 News Yes Yes
2 News Yes No
1 Surveys No
2 Surveys Yes Yes
1 Events Yes
3 News No No

Which I want to end up as follows (unique row by Member ID).

For added complexity, the rules for the final table values for each CommType:

(Yes if both Consent and Emailable = Yes for CommType)
(No if Emailable = No for CommType)
(NULL if Emailable = null or no row for CommType)
Member ID News Surveys Events
1 Yes
2 No Yes
3 No

Don't know why you got downvoted - it's a good question and you clearly took the time to write it out with as much context as possible.

You can try the following - note this assumes you have a reasonable number of different CommTypes and you know all the possible values:

SELECT member_id
, MIN(CASE WHEN CommType='News' THEN CASE WHEN Consent = 'Yes' AND Emailable='Yes' THEN 'Yes' WHEN Emailable = 'No' THEN 'No' END END) AS news
, MIN(CASE WHEN CommType='Surveys' THEN CASE WHEN Consent = 'Yes' AND Emailable='Yes' THEN 'Yes' WHEN Emailable = 'No' THEN 'No' END END) AS surveys
, MIN(CASE WHEN CommType='Events' THEN CASE WHEN Consent = 'Yes' AND Emailable='Yes' THEN 'Yes' WHEN Emailable = 'No' THEN 'No' END END) AS events
-- , ..., do the same for each possible CommType
FROM your_table
GROUP BY member_id

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