2017-12-06 25 views
0
select starttime, (select count(trackid) c2 from playlistitem p1 where 
p2.radiobroadcastid = p1.radiobroadcastid) from radiobroadcast p2 

출력 :PostgreSQL 하위 쿼리 출력에서 ​​WHERE를 사용하는 방법은 무엇입니까?

Starttime    c2 
2011-10-14 20:00:00.0 42 
2011-10-20 20:00:00.0 43 
2011-10-07 09:00:00.0 7 

난 단지 (여기 43 그게 전부) 나에게 C2 컬럼의 MAX를 보여주고 싶어요. c2가 열로 정의되지 않은 경우 어떻게합니까?

편집 : 아마 HAVING에 카운트 부울 만 보여 MAX 값 어쨌든

select starttime, count(trackid) from radiobroadcast inner join playlistitem 
using(radiobroadcastid) GROUP by starttime HAVING count(*) > 100 

에 의해 HAVING 및 GROUP을 사용해야합니까?

답변

0

는 그런 다음 그 별명으로 주문하고 제한 적용 할 수 별칭을 하위 쿼리의 결과를 제공해야합니다

select starttime, 
     (select count(trackid) 
     from playlistitem p1 
     where p2.radiobroadcastid = p1.radiobroadcastid) as c2 
from radiobroadcast p2 
order by c2 desc 
limit 1; 

주 당신은 같은 수를 두 개의 행이있는 경우 이 접근법을 사용하는 사람 만 볼 수 있습니다.

이 가입 문을 사용하여 가장 높은 값을 찾으려면 같은 방법 사용 : 당신이 그들 모두를보고 여러 높은 수와 무엇을 고려해야 할 경우

select starttime, 
     count(trackid) as cnt 
from radiobroadcast 
    join playlistitem using(radiobroadcastid) 
GROUP by starttime 
order by cnt desc 
limit 1; 

을, 당신은 얻을 윈도우 기능을 사용할 수 있습니다 가장 높은 수,하지만 당신은 별칭 사용하기 위해 파생 테이블에서 쿼리를 포장해야합니다 당신은 단지 하나의 행을해야 할 경우

select starttime, cnt 
from (
    select starttime, 
      count(trackid) as cnt, 
      max(count(trackid)) over() as max_cnt 
    from radiobroadcast 
     join playlistitem using(radiobroadcastid) 
    GROUP by starttime 
) t 
where cnt = max_cnt; 

을의 LIMIT 방법은 윈도우 함수를 사용하여 한 다음 일반적으로 빠르다 .

+0

별칭을 사용해도 WHERE를 사용할 때 'org.postgresql.util.PSQLException : ERROR : column "c2"does not exist "라는 별칭이 있습니다. (작품 별 주문) –

+0

@RobVanMeirvenne : 맞습니다. order by 절에서만 별칭을 사용할 수 있습니다. 하지만 order by와 limit으로 where 절은 필요 없습니다. –

+0

** 라디오 방송에서 시작 시간, count (trackid)를 선택하세요. inner join playlistitem (radiobroadcastid) GROUP을 시작 시간으로 사용하세요. 이 코드는 이제 100보다 큰 금액으로 모든 시작 시간을 표시합니다. 최대 금액 만 어떻게 선택할 수 있는지 알고 계십니까? 제 수업은 이것에 대해 아주 나쁜 설명을했습니다. –