我试图通过以下规则获取客户的地址:
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));
但是,当然,Oracle不允许在子查询中使用ORDER BY。那么我怎样才能得到我想要的结果呢?
感谢。
答案 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