当我们需要使用upper(列名)进行排序时,如何在oracle中使用带有union子句的order by子句?

时间:2012-04-25 10:28:06

标签: mysql database oracle

以下查询给出错误:

SELECT DISTINCT dealer_state
FROM A
WHERE country='SS' 
UNION
SELECT DISTINCT dealer_state
FROM B
WHERE country='SS'
ORDER BY upper(dealer_state)

如何按顺序使用upper(列)进行排序?

2 个答案:

答案 0 :(得分:2)

假设您的查询给出的“错误”是它没有按照您的预期从B的记录中排序来自A的记录,您需要将UNION查询设为子查询到执行排序的那个:

SELECT dealer_state FROM (
    SELECT dealer_state FROM A WHERE country='SS' 
  UNION
    SELECT dealer_state FROM B WHERE country='SS'
) t
ORDER BY upper(dealer_state)

答案 1 :(得分:1)

DISTINCTORDER BY中最左边的表达式必须匹配。

最简单的方法是执行以下操作:

SELECT dds FROM (
    SELECT DISTINCT dealer_state AS dds FROM A
     WHERE country='SS'
    UNION
    SELECT DISTINCT dealer_state AS dds FROM B
     WHERE country='SS') AS d
ORDER BY upper(dds);