简体   繁体   中英

How do I avoid sub-query repetitions in SQL?

I want the Min Price for purpose-A items and Max price for purpose-B items, moreover I group my items by zone.

SELECT ZONE, MIN_PRICE, MAX_PRICE --,LEFT_ZONE
  FROM 
  (SELECT MIN(PRICE) AS MIN_PRICE , ZONE  AS LEFT_ZONE
    FROM MYTABLE 
    WHERE PURPOSE = 'A'
      AND SOMETHING = 'SOMEVALUE'
    GROUP BY ZONE 
   )
    FULL OUTER JOIN 
  (SELECT MAX(PRICE) AS MAX_PRICE, ZONE_CD  
    FROM MYTABLE 
    WHERE PURPOSE = 'B'
      AND SOMETHING = 'SOMEVALUE'
    GROUP BY ZONE 
   )
  ON LEFT_ZONE = ZONE 

This query gives the output I want, but I don't like it for two reasons:

1) I want

FROM MYTABLE 
WHERE SOMETHING = 'SOMEVALUE'

to be called only once.

2) I get ZONE null when the row comes from the right table in my full outer join.

How could I fix these problems.

Are there some more issues in my query?

Have you tried using a CASE expression to get this:

select zone,
  min(case when PURPOSE = 'A' then price end) min_price,
  max(case when PURPOSE = 'B' then price end) max_price
from MYTABLE 
where SOMETHING = 'SOMEVALUE'
group by zone

Try this:

  SELECT 
    ZONE, 
    SUM (CASE WHEN PURPOSE = 'A' THEN MIN(PRICE) ELSE 0 END) AS MIN_PRICE,
    SUM (CASE WHEN PURPOSE = 'B' THEN MAX(PRICE) ELSE 0 END) AS MAX_PRICE
  FROM 
    MYTABLE 
  WHERE 
    SOMETHING = 'SOMEVALUE'
  GROUP BY 
    ZONE 

or any small variation of this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM