Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have custom GROUP BY for MySQL query?

Tags:

mysql

group-by

I have been trying to find the simplest way to group the two age groups in my query. Is it possible for something like this to work?

SELECT age,
sum(case when age < '20' then 1 else 0 end),
sum(case when age > '20' then 1 else 0 end)
FROM Contact
GROUP BY ...."custom group one"......"custom group one".....??

I know you should group on a column usually, but in my case I that doesn't work. Any suggestions? Thx!

Table:            Desired Query Result:
Name    Age       0           1
John    18        Under 20    2
Harry   22        Over 20     2
Mary    17
Megan   27

SOLVED:

SELECT CASE
  WHEN age = '21' THEN 'young'
  WHEN  age BETWEEN '22' AND '60' THEN 'middle'                          
  ELSE 'old'
END, Count(id)
FROM  Contact
GROUP BY CASE
  WHEN age = '21' THEN 'young'
  WHEN  age BETWEEN '22' AND '60' THEN 'middle'                       
  ELSE 'old'
END

Note: AS can be used to assign alias to grouping conditions in SELECT statement and hence avoid repeating conditions twice, i.e.

SELECT CASE
  WHEN age = '21' THEN 'young'
  WHEN  age BETWEEN '22' AND '60' THEN 'middle'                          
  ELSE 'old'
END AS age_range, Count(id)
FROM  Contact
GROUP BY age_range
like image 775
user1218172 Avatar asked Nov 26 '13 06:11

user1218172


People also ask

What can I use instead of GROUP BY in MySQL?

The HAVING clause is used instead of WHERE with aggregate functions. While the GROUP BY Clause groups rows that have the same values into summary rows. The having clause is used with the where clause in order to find rows with certain conditions.

Does MySQL have grouping sets?

Starting with MySQL 8.0. 1, the server supports the SQL GROUPING function. The GROUPING function is used to distinguish between a NULL representing the set of all values in a super-aggregate row (produced by a ROLLUP operation) from a NULL in a regular row.

Can we use two GROUP BY in same query?

Yes, it is possible to use MySQL GROUP BY clause with multiple columns just as we can use MySQL DISTINCT clause. Consider the following example in which we have used DISTINCT clause in first query and GROUP BY clause in the second query, on 'fname' and 'Lname' columns of the table named 'testing'.

Can we use * in GROUP BY?

You can, but the "GROUP BY" clause is used for grouping together sets of rows, so it does not make sense for your question (or anything that involves a "SELECT *").


1 Answers

So that will be:

SELECT 
  COUNT(1), 
  age>20 AS Above20 
FROM t 
GROUP BY age>20

-check this fiddle.

Or, alternatively, with SUM() and with column view:

SELECT
  SUM(IF(age>20, 1, 0)) AS Above20,
  SUM(IF(age<=20, 1, 0)) AS Below20
FROM 
  t

-check this fiddle.

like image 190
Alma Do Avatar answered Oct 01 '22 22:10

Alma Do