HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

simple question about group by and custom groups

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
simplegroupsgroupcustomaboutandquestion

Problem

Imagine a MySQL table that only has 2 columns: an id and a name of a color.

With this query, I know how many id's I have for each color:

SELECT color_name, count(id) FROM color_table GROUP BY (color_name)

red:    10 
blue:   5 
yellow: 3
green:  1


My question is, is there a way I can specify to the "group by" some custom groups?? I mean, is there a query that results in this:

red: 10
colors different than red: 9

Solution

Not sure about MYSQL but you can use a CASE in the Group BY with SQL Server.

SELECT  CASE color_name
      WHEN 'red' THEN 'red'
      ELSE 'colors different than red'
    END AS color_group
   ,Count(id)
FROM    color_table
GROUP BY CASE color_name
      WHEN 'red' THEN 'red'
      ELSE 'colors different than red'
    END

Code Snippets

SELECT  CASE color_name
      WHEN 'red' THEN 'red'
      ELSE 'colors different than red'
    END AS color_group
   ,Count(id)
FROM    color_table
GROUP BY CASE color_name
      WHEN 'red' THEN 'red'
      ELSE 'colors different than red'
    END

Context

StackExchange Database Administrators Q#18902, answer score: 5

Revisions (0)

No revisions yet.