按列条件的SQL查询(分组)

时间:2012-07-11 14:45:15

标签: sql

如果我想进行查询以获取分组年龄的用户数

每年只计算一次计数:

select count(*) 
from tbl_user 
group by age 

我如何制作一个自定义组,以便我可以在范围内获得年龄...例如... 像这个例子:

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

4 个答案:

答案 0 :(得分:5)

在子查询中使用CASE表达式并在外部查询中按该表达式分组:

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

答案 1 :(得分:3)

SUM 1和CASE WHEN在MS SQL Server中工作,您使用的是哪个版本的SQL?

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

答案 2 :(得分:1)

您可以使用CASE声明:

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

这会将数据“压平”成一行 - 每个分组获得一行,使用它作为视图的基础,然后从中选择。

答案 3 :(得分:1)

数据属于表,而不是代码。年龄类别是数据,恕我直言。

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
        ;