我有一张学生表:
id | age
--------
0 | 25
1 | 25
2 | 23
我想查询所有的学生,和一个额外的列,计算有多少学生是相同的年龄:
id | age | count
----------------
0 | 25 | 2
1 | 25 | 2
2 | 23 | 1
最有效的方法是什么?我担心子查询会很慢,我想知道是否有更好的方法。是吗?
我有一张学生表:
id | age
--------
0 | 25
1 | 25
2 | 23
我想查询所有的学生,和一个额外的列,计算有多少学生是相同的年龄:
id | age | count
----------------
0 | 25 | 2
1 | 25 | 2
2 | 23 | 1
最有效的方法是什么?我担心子查询会很慢,我想知道是否有更好的方法。是吗?
当前回答
我会这样做:
select
A.id, A.age, B.count
from
students A,
(select age, count(*) as count from students group by age) B
where A.age=B.age;
其他回答
这应该可以工作:
您可以获取所有row表并计算行。
Select *,count(*) over() from students;
我会这样做:
select
A.id, A.age, B.count
from
students A,
(select age, count(*) as count from students group by age) B
where A.age=B.age;
select s.id, s.age, c.count
from students s
inner join (
select age, count(*) as count
from students
group by age
) c on s.age = c.age
order by id
这应该可以工作:
SELECT age, count(age)
FROM Students
GROUP by age
如果你也需要id,你可以包括上面的子查询,像这样:
SELECT S.id, S.age, C.cnt
FROM Students S
INNER JOIN (SELECT age, count(age) as cnt
FROM Students
GROUP BY age) C ON S.age = C.age
如果你使用的是Oracle,那么一个叫做“分析”的功能就可以发挥作用。它是这样的:
select id, age, count(*) over (partition by age) from students;
如果你不使用Oracle,那么你需要加入到计数:
select a.id, a.age, b.age_count
from students a
join (select age, count(*) as age_count
from students
group by age) b
on a.age = b.age