oracle子查询在where子句中有order by

时间:2014-07-08 19:44:46

标签: sql oracle subquery

我试图通过以下规则获取客户的地址:

  1. 获取首选地址(preferred_ind =' Y')
  2. 如果是多个首选地址,请先获得一个(max(address_id)正常)
  3. 如果没有首选地址,那么只需获得第一个(max(address_id)就可以了。)
  4. 如果没有地址,只需返回没有地址信息的客户名称。
  5. preferred_ind可以是' Y',' N'或null。

    SELECT c.first_name,
           c.last_name,
           a.address_line_1,
           a.city,
           a.state_code,
           a.postal_code
    FROM my_customer c,
         my_customer_address a
    WHERE c.customer_id = a.customer_id(+)
    AND (a.address_id IS NULL OR a.address_id = (SELECT MAX(a2.address_id)
                                                 FROM my_customer_address a2
                                                 WHERE a2.customer_id = c.customer_id
                                                 ORDER BY nvl(a2.preferred_ind, 'N') DESC));
    
  6. 但是,当然,Oracle不允许在子查询中使用ORDER BY。那么我怎样才能得到我想要的结果呢?

    感谢。

1 个答案:

答案 0 :(得分:0)

您应该重写为ANSI Outer Join语法并应用ROW_NUMBER:

--untested
SELECT c.first_name,
       c.last_name,
       a.address_line_1,
       a.city,
       a.state_code,
       a.postal_code
FROM my_customer c
LEFT JOIN 
 (
   SELECT customer_id,
       address_line_1,
       city,
       state_code,
       postal_code,
       ROW_NUMBER() 
       OVER (PARTITION BY customer_id
             ORDER BY preferred_ind = 'Y' DESC, address_id DESC) AS rn
   FROM my_customer_address
 ) a
ON c.customer_id = a.customer_id
AND a.rn = 1