2009-07-28 2 views
3

PostgreSQL을 사용하는 집계와 관련된 SQL 쿼리를 만드는 데 어려움을 겪고 있습니다. 다음 표를 고려 ​​PostgreSQL을 사용하여 SQL 쿼리로 집계 된 그룹의 기본 키를 가져옵니다.

CREATE TABLE thing (
    id INT NOT NULL PRIMARY KEY, 
    price NUMERIC(10,2) NOT NULL, 
    description VARCHAR(255) NOT NULL, 
    url VARCHAR(255) NOT NULL, 
    location_id INT NOT NULL REFERENCES location(id) 
) 

CREATE TABLE location (
    id INT NOT NULL PRIMARY KEY, 
    type INT NOT NULL, 
    name VARCHAR(255) NOT NULL 
) 

지금, 가장 낮은 가격이 location.type = xxx는 각 위치에 대한 모든 것을 기록을 좀하고 싶습니다. 이 날 형 XXX 각 위치에 대한 최저 가격 나열합니다,하지만 어떻게 테이블 일에서 이러한 열의 행 (또는 기본 키)를 얻을 수

SELECT min(price) FROM thing 
INNER JOIN location ON (thing.location_id = location.id) 
WHERE type = xxx 
GROUP BY location_id 

: 같은

뭔가?

답변

5

사용이 PostgreSQL 확장 :

SELECT DISTINCT ON (location.id) thing.* 
FROM location 
JOIN thing 
ON  thing.location_id = location_id 
WHERE type = 1 
ORDER BY 
     location.id ASC, price ASC 

이 각 location.id에 대한 첫 번째 행을 선택합니다.

행이 location.id 순으로 정렬되고 price 순으로 정렬되므로 최소 가격의 행이됩니다.

SELECT * 
FROM (
     SELECT thing.*, ROW_NUMBER() OVER (PARTITION BY location_id ORDER BY price) AS rn 
     FROM location 
     JOIN thing 
     ON  thing.location_id = location_id 
     WHERE type = 1 
     ) q 
WHERE rn = 1 
+0

완벽한, 즉 내가 찾던 정확히 무엇을보십시오. – Haes

0

는 아마도

SELECT t.id,t.description,t.price FROM 
    (SELECT location_id, min(price) FROM thing 
     INNER JOIN location ON (thing.location_id = location.id) 
     WHERE type = xxx 
     GROUP BY location_id 
    ) AS lowest 
    INNER JOIN thing AS t 
    ON t. location_id = lowest.location_id; 
0

가 나는 SQL 서버 사람에게있어 하위 쿼리를 사용하지만, 다음은 SQL-92해야한다 : 새로운 PostgreSQL 8.4에서

은 또한 윈도우 기능을 사용할 수 있습니다 준수해야하며 작동해야 함 :

select th.* 
from thing th 
    inner join (select lo.id, min(th.price) minPrice 
       from location lo 
       inner join thing th 
       on th.location_id = lo.id 
       where lo.type = xxx 
       group by lo.id) minSet 
    on minSet.id = th.location_id 
    and th.price = minSet.minPrice 

테스트 할 테이블이 없으므로 여기에 오타가있을 수 있습니다.

작동하는 동안 분명히 어색해 보입니다. Postgres에 SQL의 순위 함수와 같은 것이 있으면 그것들을 조금 더 단순하게 만들 것입니다.

+0

그게 내가 원래 생각해 낸 것입니다. 이 쿼리의 문제점은 최저 가격이 고유하지 않은 경우 위치에 대해 여러 가지 항목을 반환한다는 것입니다. – Haes

+0

설명에 따르면, 나는 그것이 당신이 찾고있는 것이라고 생각했습니다. 최저 가격을 기준으로 중복되는 항목이있는 경우 어떤 것을 선택 하시겠습니까? (수사적 질문, 이미 답변을 가지고 있으므로 row_number()는 매우 유용한 확장입니다.) –

3

이 쿼리

select thing.id,thing.description,thing.url,low.location_id,low.minimum from 
(select thing.location_id,min(price) as minimum from thing 
join location on thing.location_id=location.id 
    where location.type = 13 group by location_id) as low 
    inner join thing on thing.location_id = low.location_id 
관련 문제