I am trying to do something like (psuedo - of course):
SELECT
city,
CASE WHEN COUNT( [group] ) > 1 THEN 'Multiple' ELSE [group] END AS Type
FROM
offices
GROUP BY
city
Where offices contains rows like:
ID | group | city
----------------------
1 | 'A' | 'Houston'
2 | 'B' | 'Houston'
3 | 'C' | 'Houston'
4 | 'S' | 'Boston'
5 | 'R' | 'Detroit'
and result would look something like:
city | group
--------------------
'Houston'| 'Multiple'
'Boston' | 'S'
'Detroit'| 'R'
I know you can do:
SELECT
City,
CASE WHEN COUNT([group]) > 1 THEN
'Multiple'
ELSE
( SELECT [group] FROM test WHERE t.City = city )
END AS CGroup
FROM
test t
GROUP BY
City
I thought this should be simpler.
Something without a sub query?
You can find the MIN and MAX of the column and then act if they are not identical:
declare @t table (ID int not null,[group] char(1) not null,city varchar(20) not null)
insert into @t(ID,[group],city) values
(1,'A','Houston'),
(2,'B','Houston'),
(3,'C','Houston'),
(4,'S','Boston' ),
(5,'R','Detroit')
select city,
CASE
WHEN MIN([group]) != MAX([group]) THEN 'Multiple'
ELSE MAX([group]) END as [group]
from @t
group by city
The server should be smart enough to only actually run the MAX aggregate once despite it appearing twice in the select clause.
Result:
city group
-------------------- --------
Boston S
Detroit R
Houston Multiple
@Damien_The_Unbeliever's answer is perfect. This one is an alternative. If you want to check for more than one (e.g. COUNT(GROUP) > 2). Just use MIN or MAX in ELSE like this:
SELECT
city,
CASE WHEN COUNT([group]) > 2
THEN 'Multiple'
ELSE MAX([group]) END AS Type
FROM
offices
GROUP BY
city
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With