使用聚合函数查找计数 sql
finding count using aggregate function sql
对于给定的数据,我需要找出工资低于 avg(salary)
的 id 计数
id salary
1 11
2 12
2 14
1 12
1 13
1 14
1 15
所以我的最终输出会是这样的
id count
1 2
2 1
[id 1 的平均工资是 13,id 2 的平均工资是 13。所以 id 1 中有两个值小于 id 2 的平均工资]
GROUP BY with COUNT(*) 计数,检查 WHERE < AVG using sub-select:
select id, count(*)
from tablename
where salary < (select avg(salary) from tablename)
group by id
select id , count(salary)
from tablename
group by id
having salary < avg(salary)
此查询将为您提供低于每个 ID 平均工资的工资计数。
希望你只想要这个。
我倾向于为此使用 window 函数:
select id, count(*) as cnt
from (select t.*, avg(salary) over (partition by id) as avgs
from table t
) t
where salary < avgs
group by id;
对于给定的数据,我需要找出工资低于 avg(salary)
的 id 计数id salary
1 11
2 12
2 14
1 12
1 13
1 14
1 15
所以我的最终输出会是这样的
id count
1 2
2 1
[id 1 的平均工资是 13,id 2 的平均工资是 13。所以 id 1 中有两个值小于 id 2 的平均工资]
GROUP BY with COUNT(*) 计数,检查 WHERE < AVG using sub-select:
select id, count(*)
from tablename
where salary < (select avg(salary) from tablename)
group by id
select id , count(salary)
from tablename
group by id
having salary < avg(salary)
此查询将为您提供低于每个 ID 平均工资的工资计数。
希望你只想要这个。
我倾向于为此使用 window 函数:
select id, count(*) as cnt
from (select t.*, avg(salary) over (partition by id) as avgs
from table t
) t
where salary < avgs
group by id;