patternsqlMinor
simple question about group by and custom groups
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:
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:
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: 1My 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: 9Solution
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'
ENDCode 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'
ENDContext
StackExchange Database Administrators Q#18902, answer score: 5
Revisions (0)
No revisions yet.