Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top