by 기리 [SQL Query] postgre sql join column 재사용 [2017.11.26 22:45:36]
SELECT
t1.coid,
t1.prdcd,
t1.prdctgcd,
t1.salsdd,
t1.saledd,
t1.seqno,
t1.unit,
t1.qt,
t1.salpric,
t1.dc,
t1.cntrbaccrt,
t1.saleqt,
t1.salsqt,
t2.prdnm,
t3.prdctgnm,
t2.prdspec,
t4.hprdctgnm,
t4.prdctgnm
FROM
(select * from smo_salprd WHERE
to_date(salsdd, 'YYYYMMDD') <= to_date(to_char(now(), 'YYYYMMDD'), 'YYYYMMDD') AND
to_date(saledd, 'YYYYMMDD') >= to_date(to_char(now(), 'YYYYMMDD'), 'YYYYMMDD')
) as t1 , smo_prd t2, smo_prdctg t3,
(select a.prdctgcd aprdctgcd, b.prdctgcd, b.hprdctgnm, b.prdctgnm from smo_prd a,
(select ta3.* from (select ta1.*,ta2.prdctgnm as hprdctgnm from smo_prdctg ta1, smo_prdctg ta2 where ta1.hprdctgcd=ta2.prdctgcd) ta3
where ta3.hprdctgcd= substring(t1.prdctgcd,0,3)
-- where ta3.hprdctgcd= substring('01',0,3)
AND ta3.prdctgcd like substring(t1.prdctgcd, 0, 5) ||'%'
-- AND ta3.prdctgcd like substring('0101', 0, 5) ||'%'
)b
where substring(t1.prdctgcd, 0, 3)=b.hprdctgcd
-- where substring('01', 0, 3)=b.hprdctgcd
)t4
WHERE t1.prdcd=t2.prdcd
AND t1.coid=t2.coid
AND t1.prdctgcd=t2.prdctgcd
AND t1.prdctgcd=t3.prdctgcd
AND t4.aprdctgcd=t1.prdctgcd
AND t2.prdspec LIKE '%' || '체크' || '%'
OR t2.prdnm LIKE '%' || '체크'|| '%'
OR t3.prdctgnm LIKE '%' || '체크' || '%'
substring으로 t1.prdctgcd에서 숫자를 추출해서 쓰고 싶습니다.
그런데 위 쿼리를 쓰니 아래처럼 에러가 나네요
쿼리를 어떻게 바꿔야될지 도움 구합니다.
ERROR: invalid reference to FROM-clause entry for table "t1"
LINE 27: where ta3.hprdctgcd= substring(t1.prdctgcd,...
^
HINT: There is an entry for table "t1", but it cannot be referenced from this part of the query.
********** Error **********
ERROR: invalid reference to FROM-clause entry for table "t1"
SQL state: 42P01
Hint: There is an entry for table "t1", but it cannot be referenced from this part of the query.
Character: 972
t4는 상품의 상위카테고리명을 가져오려는 문단입니다.
1. to_date 가 소모적으로 사용된 듯 하구요.
2. OR 사용시 괄호에 유의해야 합니다.
3. t4 가 너무 복잡합니다.
SELECT t1.coid , t1.prdcd , t1.prdctgcd , t1.salsdd , t1.saledd , t1.seqno , t1.unit , t1.qt , t1.salpric , t1.dc , t1.cntrbaccrt , t1.saleqt , t1.salsqt , t2.prdnm , t3.prdctgnm , t2.prdspec , t4.prdctgnm AS hprdctgnm FROM (SELECT * FROM smo_salprd WHERE to_date(salsdd, 'YYYYMMDD') <= to_date(to_char(now(), 'YYYYMMDD'), 'YYYYMMDD') AND to_date(saledd, 'YYYYMMDD') >= to_date(to_char(now(), 'YYYYMMDD'), 'YYYYMMDD') ) AS t1 , smo_prd t2 , smo_prdctg t3 , smo_prdctg t4 WHERE t1.prdcd = t2.prdcd AND t1.coid = t2.coid AND t1.prdctgcd = t2.prdctgcd AND t1.prdctgcd = t3.prdctgcd AND t4.hprdctgcd = SUBSTRING(t1.prdctgcd, 1, 3) AND ( t2.prdspec LIKE '%' || '체크' || '%' OR t2.prdnm LIKE '%' || '체크' || '%' OR t3.prdctgnm LIKE '%' || '체크' || '%' ) ;