cooper_milton
cooper_milton

Reputation: 87

Combining multiple rows into one using group by in t/sql

I need to combine 2 rows like this:

Name     Option
John     Priority
John     Insurance

... into one like this:

Name     Option
John     Both

If there was only one row for John in the source table, then the result's Option value should be the same as in the table.

With Group By, I am not sure what goes in here:

 select Name, case when Count(Option) > 1 then 'Both' else ??? end Option
 group by Name

Upvotes: 1

Views: 42

Answers (1)

codeulike
codeulike

Reputation: 23064

If there's only one row/value then Max() will give you that value. so you could try:

select Name, case when Count(Option) > 1 then 'Both' else Max(Option) end as Option
from whatever
group by Name

This will only really make sense if you can be sure there will only ever be two options.

Upvotes: 1

Related Questions