简体   繁体   English

"如何在 SQL 中有效地计算列值的出现次数?"

[英]How to count occurrences of a column value efficiently in SQL?

I have a table of students:我有一张学生表:

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

I want to query for all students, and an additional column that counts how many students are of the same age:我想查询所有学生,以及一个计算有多少学生同龄的附加列:

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

What's the most efficient way of doing this?这样做最有效的方法是什么? I fear that a sub-query will be slow, and I'm wondering if there's a better way .我担心子查询会很慢,我想知道是否有更好的方法 Is there?在那儿?

This should work: 这应该工作:

SELECT age, count(age) 
  FROM Students 
 GROUP by age

If you need the id as well you could include the above as a sub query like so: 如果您还需要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

If you're using Oracle, then a feature called analytics will do the trick. 如果您使用的是Oracle,那么称为分析的功能就可以实现。 It looks like this: 它看起来像这样:

select id, age, count(*) over (partition by age) from students;

If you aren't using Oracle, then you'll need to join back to the counts: 如果您不使用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

Here's another solution. 这是另一种解决方案。 this one uses very simple syntax. 这个使用非常简单的语法。 The first example of the accepted solution did not work on older versions of Microsoft SQL (ie 2000) 接受的解决方案的第一个示例不适用于旧版本的Microsoft SQL(即2000)

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

I would do something like: 我会做的事情如下:

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

and if data in "age" column has similar records (ie many people are 25 years old, many others are 32 and so on), it causes confusion in aligning right count to each student. 如果“年龄”栏中的数据具有相似的记录(即许多人年龄为25岁,其他许多人为32岁等等),则会导致混淆对齐每个学生的正确计数。 in order to avoid it, I joined the tables on student ID as well. 为了避免这种情况,我也加入了学生证的表格。

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*

This should work:这应该有效:

You can fetch all row your table and count.您可以获取表格的所有行并计数。

select *,count(*) over() from students;从学生中选择 *,count(*) over();

"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM