IT story

SQL에서 열 값의 발생을 효율적으로 계산하는 방법은 무엇입니까?

hot-time 2020. 6. 13. 09:43
반응형

SQL에서 열 값의 발생을 효율적으로 계산하는 방법은 무엇입니까?


학생들의 테이블이 있습니다 :

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

모든 학생과 같은 연령의 학생 수를 계산하는 추가 열을 쿼리하고 싶습니다.

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을 사용하는 경우 분석 기능이 트릭을 수행합니다. 다음과 같이 보입니다 :

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

다른 해결책이 있습니다. 이것은 매우 간단한 구문을 사용합니다. 허용 된 솔루션의 첫 번째 예는 이전 버전의 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

and if data in "age" column has similar records (i.e. many people are 25 years old, many others are 32 and so on), it causes confusion in aligning right count to each student. 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*

참고URL : https://stackoverflow.com/questions/1503959/how-to-count-occurrences-of-a-column-value-efficiently-in-sql

반응형