如果我想进行查询以获取分组年龄的用户计数
每年单独计算:
select count(*)
from tbl_user
group by age
如何创建自定义组,以便我可以获取范围内的年龄,例如......就像这个例子:
group by ages as 0-18 , 19-25 , 26-...
如果我想进行查询以获取分组年龄的用户计数
每年单独计算:
select count(*)
from tbl_user
group by age
如何创建自定义组,以便我可以获取范围内的年龄,例如......就像这个例子:
group by ages as 0-18 , 19-25 , 26-...
在子查询中使用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
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
您可以使用以下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
这会将数据“展平”为一行 - 要为每个分组获取一行,请将此作为视图的基础,然后从中进行选择。
数据属于表格,而不是代码。年龄类别是数据,恕我直言。
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
;