Receipts (구입 명세) - 고객별로 최소 순번을 가진 레코드 구하기
cust_id | seq | price |
---|---|---|
A | 1 | 500 |
A | 2 | 1000 |
A | 3 | 700 |
B | 5 | 100 |
B | 6 | 5000 |
B | 7 | 300 |
B | 9 | 200 |
B | 12 | 1000 |
C | 10 | 600 |
C | 20 | 100 |
C | 45 | 200 |
C | 70 | 50 |
D | 3 | 2000 |
1) 서브쿼리 사용
SELECT R1.cust_id, R1.seq, R1.price
FROM Receipts R1
INNER JOIN
(SELECT cust_id, MIN(seq) AS min_seq
FROM Receipts
GROUP BY cust_id) R2
ON R1.cust_id=R2.cust_id
AND R1.seq=R2.min_seq;
2) 상관 서브쿼리
SELECT cust_id, seq, price
FROM Receipts R1
WHERE seq=(SELECT MIN(seq)
FROM Receipts R2
WHERE R1.cust_id=R2.cust_id);