Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using GROUP BY clause to replace dissimilar rows with single value

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?

like image 412
user2571540 Avatar asked Jan 25 '26 04:01

user2571540


2 Answers

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
like image 87
Damien_The_Unbeliever Avatar answered Jan 26 '26 18:01

Damien_The_Unbeliever


@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

See this SQLFiddle

like image 35
Himanshu Jansari Avatar answered Jan 26 '26 20:01

Himanshu Jansari