如何在SQL中有效地计算列值的发生?

我有一个学生的桌子:

id | age -------- 0 | 25 1 | 25 2 | 23 

我想查询所有的学生,还有一个专栏logging了同一年龄的学生人数:

 id | age | count ---------------- 0 | 25 | 2 1 | 25 | 2 2 | 23 | 1 

什么是最有效的方法呢? 我担心子查询会很慢,我想知道是否有更好的方法 。 在那儿?

这应该工作:

 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,那么称为分析function的function将会起作用。 它看起来像这样:

 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 

这是另一个解决scheme。 这个使用非常简单的语法。 接受的解决scheme的第一个例子不适用于旧版本的Microsoft SQL(即2000)

 SELECT age, count(*) FROM Students GROUP by age ORDER BY age 

我会做这样的事情:

 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 

如果“年龄”栏中的数据有相似的logging(即25岁以上的人多,32人等等),则对每个学生的权数统一会造成混乱。 为了避免这种情况,我也join了学生证的表格。

 SELECT S.id, S.age, C.cnt FROM Students S INNER JOIN (SELECT id, age, count(age) as cnt FROM Students GROUP BY student,age) C ON S.age = C.age *AND S.id = C.id*