source

하나의 행만 선택하는 동안 총 행 번호 가져오기

nicesource 2022. 11. 15. 21:38
반응형

하나의 행만 선택하는 동안 총 행 번호 가져오기

관련/비슷한 질문:MySQL - 행 번호 가져오기 선택, 부분 결과만 선택, 행 수 가져오기

현재 다음 테이블이 있습니다.

+----+--------------------+---------------+--------+
| id | accountId          | competitionId | rating |
+----+--------------------+---------------+--------+
|  1 | theidoftheaccount1 |            1  | 100    |
|  2 | theidoftheaccount2 |            3  | 90     |
|  3 | theidoftheaccount3 |            1  | 80     |
|  4 | theidoftheaccount4 |            1  | 50     |
+----+--------------------+---------------+--------+

와 싸우고 싶다.accountId='theidoftheaccount3'일반적인 SQL 문을 호출합니다.SELECT * FROM competitors WHERE competitionId='someotherid1' AND accountId='theidoftheaccount3 ' ORDER BY rating DESC모든 게 다 좋아

문제:여기서 얻은 행의 행 번호를 알고 싶은데, 이 행의 행 번호는,competitionId='someotherid1'이 행 번호는 같은 경기에서 다른 모든 선수 중 선수의 '랭크'가 된다.

그래서 기본적으로 하루의 끝에 다시 돌아오곤 했다.

+----+--------------------+---------------+--------+-----------+
| id | accountId          | competitionId | rating | rowNumber |
+----+--------------------+---------------+--------+-----------+
|  3 | theidoftheaccount3 |            1  | 80     | 2         |
+----+--------------------+---------------+--------+-----------+

이것이 어떻게 행해지는가?

한 가지 방법은row_number()서브쿼리:

select c.*
from (select c.*,
             rank() over (partition by competitionid order by rating desc) as ranking
      from competitors c
      where competitionId = 'someotherid1'
     ) c
where accountId = 'theidoftheaccount3';

편집:

창 기능이 없는 다른 방법은 다음과 같습니다.

select count(*) + 1 as ranking
from competitors c
where c.competitionId = 'someotherid1' and
      c.rating > (select c2.rating
                  from competitors c2
                  where c2.competitionid = c.competitionId and
                        c2.accountId = 'theidoftheaccount3' 
                 );

데이터베이스가 창 기능을 지원하지 않는 경우 하위 쿼리를 사용할 수도 있습니다.

select
    t.*,
    (
        select count(*) + 1
        from mytable t1
        where t1.competitionId = t.competitionId and t1.rating > t.rating
    ) row_num
from mytable t
where t.accountId = 'theidoftheaccount3' 

성능을 위해 열에 대한 인덱스를 원합니다.(competitionId, rating)(다른 하나는 컬럼에 있습니다).accountId하지만, 이것은 아마도 이미 존재하는 것 같습니다.unique열)을 클릭합니다.

언급URL : https://stackoverflow.com/questions/59603207/get-total-row-number-while-only-selecting-a-single-row

반응형