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
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
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.
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.
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'.
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 *").
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With