Sample Header Ad - 728x90

How to use GROUP BY in a way that concatenates data in one column, but filters for specific data in another

4 votes
5 answers
36261 views
I am running SQL Server 2014 I have a table that looks like this: ID | Name | AddressType | Address | Features ======================================================== 1 | Bob | Home | 123 Nope St | JP 2 | John | Work | 555 Fake St | MNGF 2 | John | Home | 654 Madeup Ln | IMP JP 3 | Kim | Work | 92 Nadda Blvd | MP I am trying to write a SQL Server query that looks for duplicate IDs and always returns the Line containing a "Work" Address, but I want it to concatenate the Features from both lines so that I get something like this: ID | Name | AddressType | Address | Features ======================================================== 1 | Bob | Home | 123 Nope St | JP 2 | John | Work | 555 Fake St | MNGF IMP JP 3 | Kim | Work | 92 Nadda Blvd | MP The closest I've been able to figure out how to get looks something like this: SELECT ID, Name, MAX(AddressType), MAX(Address), CONCAT(Features) FROM (SELECT * FROM myTable ORDER BY ID, AddressType DESC) GROUP BY ID, NAME ... but MAX(AddressType) and MAX(Address) are being pulled separately, so sometimes I get the Work Address and sometimes I get the Home Address. What I really need is the MAX(AddressType) and whatever Address is on the same line as that result. The other thing I've tried is: SELECT ID, Name, AddressType, Address, CONCAT(Features), COUNT(ID) OVER(PARTITION BY ID) AS IDcount FROM myTable GROUP BY ID, NAME WHERE AddressType = 'Work' OR IDcount = 1 ... this always gives me all the right Addresses, but filters out the Features for the "Home" AddressType so that I can not Concatenate them in.
Asked by Nosajimiki (147 rep)
Sep 13, 2021, 09:30 PM
Last activity: Apr 13, 2023, 09:13 AM