按查询排序的两个联合维护订单

时间:2014-10-10 09:17:44

标签: sql oracle11g oracle-sqldeveloper

我正在尝试运行以下查询,但看起来我做错了。

(刚刚修改了示例查询以便清楚理解)

 SELECT   name,total,rate 
 FROM     business b
 WHERE rate > 100
 ORDER BY total DESC

 UNION 

 SELECT   name,total,rate 
 FROM     business b
 WHERE  rate <= 100
 ORDER BY rate ASC

现在我希望将这两个查询联合起来,并在第一行的结果输出中输出应该来自第一个查询,然后以相同的排序顺序从第二个查询输出,但是单个实际查询正在给出。

如果还不清楚,请告诉我。我将尝试在更深层次的解释。

4 个答案:

答案 0 :(得分:1)

试试这个:

select name,total,rate
  from (
        SELECT name,total,rate, row_number() over(order by total desc) rn, 1 ord
        FROM     business b
        WHERE rate > 100

        UNION 

        SELECT   name,total,rate, row_number() over(ORDER BY rate ASC) rn, 2 ord
        FROM     business b
        WHERE  rate <= 100
       )
 order by ord, rn

答案 1 :(得分:1)

这非常简单:使用UNION ALL代替UNION

SELECT * FROM (
SELECT   name,total,rate 
FROM     business b
WHERE rate > 100
ORDER BY total DESC) x
UNION ALL
SELECT * FROM (
SELECT   name,total,rate 
FROM     business b
WHERE  rate <= 100
ORDER BY rate ASC) y

UNION ALL将订单保留为已编码。

UNION删除重复项,但不保证订单。大多数数据库实际上对输出进行排序(以使重复检测更容易)。

答案 2 :(得分:0)

编辑:尝试将条件OR子句作为here。这也将避免工会。

SELECT NAME, TOTAL, RATE FROM BUSINESS B
ORDER BY
CASE
    WHEN rate > 100 THEN total 
    WHEN rate <= 100 THEN rate 
END

不要使用多层选择查询,只需在选择查询中包含一个名为TAB_ID的附加字段,并使用该字段进行排序,如下所示:

SELECT CHAR1 FROM
(
        SELECT 'd' AS char1 , 2 AS sortcol, '1' AS TAB_ID  FROM   dual 
        UNION 
        SELECT 'c' AS char1 , 1 AS sortcol, '1' AS TAB_ID  FROM   dual
        UNION
        SELECT 'a' AS char1 , 1 AS sortcol, '2' AS TAB_ID  FROM   dual 
        UNION 
        SELECT 'b' AS char1 , 2 AS sortcol, '2' AS TAB_ID  FROM   dual
) ORDER BY TAB_ID, SORTCOL;

Working SQL Fiddle Here

检查结果

要更正原始查询并避免丢失的paranthesis错误,请使用以下查询,但它似乎没有提供正确的输出:

select * from
(
    SELECT * FROM 
    (
         SELECT 'd' AS char1 , 2 AS sortcol  FROM   dual 
         UNION 
         SELECT 'c' AS char1 , 1 AS sortcol  FROM   dual
    ) Inner1
      ORDER BY Inner1.sortcol
)
    UNION 
select * from
(
    SELECT * FROM 
    (
        SELECT 'a' AS char1 , 1 AS sortcol  FROM   dual 
        UNION 
        SELECT 'b' AS char1 , 2 AS sortcol  FROM   dual
    ) Inner2
    ORDER BY Inner2.sortcol
)   ;

答案 3 :(得分:0)

在每个内部分支中添加分支标志,并按第一个分类:

SELECT * FROM 
(
  SELECT * FROM 
  (
    SELECT 'd' AS char1 , 2 AS sortcol, 1 AS branch FROM dual 
    UNION 
    SELECT 'c' AS char1 , 1 AS sortcol, 1 AS branch FROM dual
    ORDER BY sortcol
  ) Inner1
  UNION 
  SELECT * FROM 
  (
    SELECT 'a' AS char1 , 1 AS sortcol, 2 as branch FROM dual 
    UNION 
    SELECT 'b' AS char1 , 2 AS sortcol, 2 as branch FROM dual
    ORDER BY sortcol
  ) Inner2
) Outer
ORDER BY Outer.branch, Outer.SORTCOL;

CHAR1    SORTCOL     BRANCH
----- ---------- ----------
c              1          1 
d              2          1 
a              1          2 
b              2          2 

显然,您可以将外部查询中的*替换为仅在结果集中获取所需的列,不包括branchsortcol

SQL Fiddle with both queries for comparison