쿼리질문입니다. 0 2 1,155

by 김동욱 [SQL Query] [2013.08.05 10:10:20]


DB에 저장 된 자료가

Code Name       Day   Stand
 GB    AAA   18/1  ALL 
 GB    AAA   18/1    2

형식으로 저장되어 있습니다.

자료를 select 하고 싶은데 자료는

'AAA', '18/1', '12' ,
'AAA', '18/1', '2' 형식으로 구성되어 있습니다.

Name, Day, Stand 를 기준으로 Code 값을 찾고 싶은데 Stand의 기준이 2를 제외한 경우 ALL 방식으로 처리하여

Code 값을 select 하고 싶은데 쿼리문을 어떻게 구성해야 되는지 좀 도와주세요 ㅜㅜㅜ

by 미카엘 [2013.08.05 10:44:32]
 
-- stand 기준이 2일 경우 ALL 만 
with t as (
select 'GB' code, 'AAA' nm, '18/1' day,  'ALL' stand from dual union all 
select 'GB' code, 'AAA' nm, '18/1' day,  '2'   stand from dual)
select *
  from t
 where nm = :nm
   and day = :day
   and stand = decode(:stand, '2', 'ALL')


-- stand 기준이 2일 경우 2를 제외한 전체
with t as (
select 'GB' code, 'AAA' nm, '18/1' day,  'ALL' stand from dual union all
select 'GB' code, 'AAA' nm, '18/1' day,  '5'   stand from dual union all 
select 'GB' code, 'AAA' nm, '18/1' day,  '2'   stand from dual)
select *
  from t
 where nm = :nm
   and day = :day
   and stand <> decode(:stand, '2', :stand)
   
-- stand '2' 제외
with t as (
select 'GB' code, 'AAA' nm, '18/1' day,  'ALL' stand from dual union all 
select 'GB' code, 'AAA' nm, '18/1' day,  '2'   stand from dual)
select *
  from t
 where nm = :nm
   and day = :day
   and stand <> '2' 
--(stand 제외 기준이 늘어나면 not in ('2', '3'))


-- stand 기준이 ALL
with t as (
select 'GB' code, 'AAA' nm, '18/1' day,  'ALL' stand from dual union all 
select 'GB' code, 'AAA' nm, '18/1' day,  '2'   stand from dual)
select *
  from t
 where nm = :nm
   and day = :day
   and stand =  'ALL' 

by 마농 [2013.08.05 14:40:36]
WITH code_t AS
(
SELECT 'GBA' code, 'AAA' name, '18/1' day, 'ALL' stand FROM dual
UNION ALL SELECT 'GB2', 'AAA', '18/1', '2' FROM dual
UNION ALL SELECT 'GB1', 'AAA', '18/1', '1' FROM dual
)
, data_t AS
(
SELECT 'AAA' name, '18/1' day, '12' stand FROM dual
UNION ALL SELECT 'AAA', '18/1', '1' FROM dual
UNION ALL SELECT 'AAA', '18/1', '2' FROM dual
UNION ALL SELECT 'AAA', '18/1', '3' FROM dual
)
SELECT a.name, a.day, a.stand
     , NVL(b.code, c.code) code
  FROM data_t a
     , code_t b
     , code_t c
 WHERE b.name (+) = a.name
   AND b.day  (+) = a.day
   AND b.stand(+) = a.stand
   AND c.name (+) = a.name
   AND c.day  (+) = a.day
   AND c.stand(+) = 'ALL'
;
댓글등록
SQL문을 포맷에 맞게(깔끔하게) 등록하려면 code() 버튼을 클릭하여 작성 하시면 됩니다.
로그인 사용자만 댓글을 작성 할 수 있습니다. 로그인, 회원가입