如何避免SQL中的子查询重复?

时间:2013-03-01 13:50:48

标签: sql subquery full-outer-join

我想要最低价格用于目的 - 物品和最高价格 对于目的-B项目,而且我按区域对项目进行分组。

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 

此查询提供了我想要的输出,但我不喜欢它 有两个原因:

1)我想要

FROM MYTABLE 
WHERE SOMETHING = 'SOMEVALUE'

只能被召唤一次。

2)当行来自右表时,我得到ZONE null 在我的完全外部联接。

我怎样才能解决这些问题。

我的查询中是否还有其他问题?

2 个答案:

答案 0 :(得分:3)

您是否尝试使用CASE表达式来实现此目的:

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

答案 1 :(得分:0)

试试这个:

  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 

的任何小变化