Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

group by in sql combining values [closed]

I have a table (sql 2008) with A,B,C,D,E values in col1 Is there a way to get counts grouped by col1 so that result returned will be

A - #
B - #
other - #

Thank you

like image 355
chibis Avatar asked Feb 22 '26 01:02

chibis


2 Answers

Repeating the CASE expression works, but I find it a little less tedious to only perform that expression once. Plans are identical.

;WITH x AS 
(
  SELECT Name = CASE WHEN Name IN ('A','B') THEN Name 
  ELSE 'Other' END
  FROM dbo.YourTable
)
SELECT Name, COUNT(*) FROM x 
GROUP BY Name;

If ordering is important (e.g. Other should be the last row in the result, even if other names come after it alphabetically), then you can say:

ORDER BY CASE WHEN Name = 'Other' THEN 1 ELSE 0 END, Name;
like image 115
Aaron Bertrand Avatar answered Feb 23 '26 18:02

Aaron Bertrand


select
   case when col1 in ('a','b') then col1 else 'other' end,
   count(*)
from tab
group by case when col1 in ('a','b') then col1 else 'other' end
like image 43
dnoeth Avatar answered Feb 23 '26 18:02

dnoeth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!