database.sarang.net
UserID
Passwd
Database
DBMS
MySQL
PostgreSQL
Firebird
Oracle
Informix
Sybase
ㆍMS-SQL
DB2
Cache
CUBRID
LDAP
ALTIBASE
Tibero
DB 문서들
스터디
Community
공지사항
자유게시판
구인|구직
DSN 갤러리
도움주신분들
Admin
운영게시판
최근게시물
MS-SQL Q&A 5928 게시물 읽기
No. 5928
그룹별 상위 n개 조회쿼리 질문
작성자
네로
작성일
2011-08-09 11:55
조회수
9,041

고객번호 매출월 청구금액 수금여부
00001  201101 50000  0
00001  201102 50000  1
00001  201103 50000  1
00002  201101 50000  0
00002  201102 50000  0
00002  201103 50000  1
00002  201104 50000  0
00002  201105 50000  1


위는 매출자료를 저장하는 테이블입니다.
수금이 안된 자료를 조회해야하는데..

한 고객에 대해서 최대 2개 까지만 가져와야 합니다

고객번호 별로 union join 쿼리식을 만들기에는
고객수가 너무 많아서...
다른 방법이 없을까요?

이 글에 대한 댓글이 총 3건 있습니다.
with t as (
select '00001' userid,  '201101' sdate, 50000 amt, '0' gb from dual
union all
select '00001' userid,  '201102' sdate, 50000  amt, '1' gb from dual
union all
select '00001' userid,  '201103' sdate, 50000  amt, '1' gb from dual
union all
select '00001' userid,  '201104' sdate, 50000  amt, '0' gb from dual
union all
select '00001' userid,  '201105' sdate, 50000  amt, '0' gb from dual
union all
select '00002' userid,  '201101' sdate, 50000  amt, '0' gb from dual
union all
select '00002' userid,  '201102' sdate, 50000  amt, '0' gb from dual
union all
select '00002' userid,  '201103' sdate, 50000  amt, '1' gb from dual
union all
select '00002' userid,  '201104' sdate, 50000  amt, '0' gb from dual
union all
select '00002' userid,  '201105' sdate, 50000  amt, '1' gb from dual
union all
select '00002' userid,  '201106' sdate, 50000  amt, '0' gb from dual
union all
select '00003' userid,  '201101' sdate, 50000  amt, '0' gb from dual
union all
select '00003' userid,  '201102' sdate, 40000  amt, '0' gb from dual
union all
select '00003' userid,  '201103' sdate, 40000  amt, '0' gb from dual
)
select * from t a where gb='0'
and exists (select 1 from t b where b.gb='0' and a.userid = b.userid and a.sdate>=b.sdate having count(*)<=2) 
 
 
2 를 다른값으로 바꿔보시면 됩니다.
 
1님이 2011-08-09 13:58에 작성한 댓글입니다. Edit

고객번호가 10000개에 테이블에 데이터가 100만개 정도 되는데..

union은 힘들것 같습니다.

네로님이 2011-08-09 15:47에 작성한 댓글입니다. Edit

저기....  위에 with 절부터  괄호 ')' 까지는 데이터 생성을 위한 예문이구요..

select * from t  ....  

이부분부터만 t 를 테이블명으로 바꾸시고 필드명 변경하셔서 쓰시면 됩니다만... 

1님이 2011-08-09 16:40에 작성한 댓글입니다. Edit
[Top]
No.
제목
작성자
작성일
조회
5931두개의 문자열 비교하여, 위치별 틀린 갯수 구하기 [1]
dol
2011-08-11
7502
5930한가지 더 질문드리겠습니다. 여러로우의 텍스트값을 하나의 로우에 붙여서 출력하고자 합니다. [3]
최명근
2011-08-10
7337
5929질문입니다. GROUP BY 사용하여 데이터 가로로 뽑고자 합니다. [2]
최명근
2011-08-10
8020
5928그룹별 상위 n개 조회쿼리 질문 [3]
네로
2011-08-09
9041
5927마지막 주 주말 구하기? [2]
낭자
2011-08-04
7446
5926mssql 쿼리 질문입니다. [4]
안효수
2011-08-04
6584
5925원격 서버 데이터베이스 접근 Select [1]
김명호
2011-08-03
6198
Valid XHTML 1.0!
All about the DATABASE... Copyleft 1999-2024 DSN, All rights reserved.
작업시간: 0.020초, 이곳 서비스는
	PostgreSQL v16.2로 자료를 관리합니다