SQL Assistance - Grouping other fields by common email

荒凉一梦 提交于 2019-12-11 07:46:37

问题


I'd appreciate any assistance people could provide with this one. I've tried to follow a couple of other posts (GROUP BY to combine/concat a column), but when I do this, it combines everything.

I have a table in SQL that holds contact data. Some contacts in the database have the same email address, particularly admin@, accounts@, etc. We also have a list of contact preferences for each contact: Emergency Contact, Accounts, WHS, etc. I'm trying to select the results of the table, but only one row per email address.

My data looks like this:

However, I'd like it to group the rows together that have the same email address (I don't care about the names). I'd also like it to look at the contact preference fields and if even one of the joined fields had a yes, show a Y, otherwise show a N - see below example

As I mentioned, all my tests have been unsuccessful I'm afraid, so I would appreciate any assistance that you can provide.

Thank you

Luke


回答1:


You can use the following:

;WITH selected as (
select min(ContactID) as ContactID, Mail, max(EmergencyContact) as EmergencyContact, 
max(AccountsCon) as AccountsCon, max(WHSContact) as WHSContact
from t
GROUP BY Mail
)
select t.ContactID, t.BusinessID, t.BusinessName, t. FirstName, t.LastName, t.Position, t.Mail, s.EmergencyContact, s.AccountsCon, s.WHSContact
from selected as s
inner join t as t ON t.ContactID = s.ContactID

This way you get the contactid, businessid, businessname, firstname, lastname and position from the first record found with each email and the last 3 columns you get using max (taking advantage that Y is greater than N, so if there is at least one Y it will get Y).




回答2:


I think you can just use aggregation:

select businessid, businessname, max(firstname),
       max(lastname), max(position),
       email,
       max(emergencycontact),
       max(accountscor),
       max(whcontact)
from t
group by businessid, businessname, email;


来源:https://stackoverflow.com/questions/57237434/sql-assistance-grouping-other-fields-by-common-email

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!