简体   繁体   中英

SQL query to (group by ) by condition of column

if I want to make a query that gets the count of users grouping ages

to get the counts each year as alone :

select count(*) 
from tbl_user 
group by age 

how can I make a custom group by so I can get ages in ranges for example ... like this example :

group by ages as 0-18 , 19-25 , 26-...

Use a CASE expression in a subquery and group by that expression in the outer query:

select age_group, count(*) 
from (
  select case when age between  0 and 18 then '0-18'
              when age between 19 and 26 then '19-25'
              ...
              end as age_group
  from tbl_user
) t
group by age_group

SUM 1 and CASE WHEN work in MS SQL Server, which version of SQL are you using?

SELECT
    SUM(CASE WHEN Age >= 0 AND Age <= 18 THEN 1 ELSE 0 END) AS [0-18],
    SUM(CASE WHEN Age >= 19 AND Age <= 25 THEN 1 ELSE 0 END) AS [19-25]
FROM
    YourTable

You could use a CASE statement:

SELECT Sum(CASE WHEN age BETWEEN 0 AND 18 THEN 1 ELSE 0 END) as [0-18],
Sum(CASE WHEN age BETWEEN 19 AND 25 THEN 1 ELSE 0 END) as [19-25],
Sum(CASE WHEN age BETWEEN 26 AND 34 THEN 1 ELSE 0 END) as [26-34]
FROM tbl_user

this will "flatten" the data into one row - to get one row per grouping use this as the basis for a View, then select from that.

Data belongs in a table, not in the code. The age categories are data, IMHO.

CREATE TABLE one
        ( val SERIAL NOT NULL PRIMARY KEY
        , age INTEGER NOT NULL
        );
INSERT INTO one (age) SELECT generate_series(0,31, 1);

CREATE TABLE age_category
        ( low INTEGER NOT NULL PRIMARY KEY
        , high INTEGER NOT NULL
        , description varchar
        );
INSERT INTO age_category (low,high,description) VALUES
   ( 0,19, '0-18')
 , ( 19,26, '19-25')
 , ( 26,1111, '26-...')
        ;

SELECT ac.description, COUNT(*)
FROM one o
JOIN age_category ac ON o.age >= ac.low AND o.age < ac.high
GROUP BY ac.description
        ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM