混合union all查询的结果并逐行排序

时间:2018-05-14 21:34:50

标签: sql oracle sql-order-by

如果问题的标题不清楚,我道歉。

我有这个示例查询:

SELECT a.i_id,
       a.i_item,
       a.i_count
  FROM abc a
 WHERE i_id = 123
UNION ALL
SELECT b.j_id,
       b.j_item,
       b.j_count
  FROM def b
 WHERE j_id = 4567

返回截屏1中的结果。 enter image description here

我想修改查询,以便它可以返回屏幕截图2中显示的内容。 enter image description here

4 个答案:

答案 0 :(得分:1)

DERIVED TABLE SORTING

select * from 
(    SELECT a.i_id,
           a.i_item,
           a.i_count
      FROM abc a
     WHERE i_id = 123
    UNION ALL
    SELECT b.j_id,
           b.j_item,
           b.j_count
      FROM def b
     WHERE j_id = 4567
) X
order by i_item

答案 1 :(得分:0)

假设在您的真实示例中,您不能仅仅ORDER BY i_itemORDER BY i_count获得所需的订单:

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE abc ( i_id, i_item, i_count ) AS
SELECT 123, 'apple',  100 FROM DUAL UNION ALL
SELECT 123, 'banana', 200 FROM DUAL UNION ALL
SELECT 123, 'candy',  300 FROM DUAL;

CREATE TABLE def ( j_id, j_item, j_count ) AS
SELECT 4567, 'apple',  100 FROM DUAL UNION ALL
SELECT 4567, 'banana', 200 FROM DUAL UNION ALL
SELECT 4567, 'candy',  300 FROM DUAL;

查询1

SELECT i_id,
       i_item,
       i_count
FROM   (
  SELECT i_id,
         i_item,
         i_count,
         ROWNUM,
         1
    FROM abc
   WHERE i_id = 123
  UNION ALL
  SELECT j_id,
         j_item,
         j_count,
         ROWNUM,
         2
    FROM def
   WHERE j_id = 4567
  ORDER BY 4, 5
)

<强> Results

| I_ID | I_ITEM | I_COUNT |
|------|--------|---------|
|  123 |  apple |     100 |
| 4567 |  apple |     100 |
|  123 | banana |     200 |
| 4567 | banana |     200 |
|  123 |  candy |     300 |
| 4567 |  candy |     300 |

答案 2 :(得分:0)

创建视图并使用以下简单查询:

CREATE VIEW ghi AS
SELECT a.i_id,
       a.i_item,
       a.i_count
  FROM abc a
 WHERE i_id = 123
UNION ALL
SELECT b.j_id,
       b.j_item,
       b.j_count
  FROM def b
 WHERE j_id = 4567;  

SELECT *
  FROM ghi
 ORDER BY  i_item, i_id;

SQL Fiddle Demo

答案 3 :(得分:0)

如果没有ORDER BY子句,查询结果的顺序就完全没有了。如果结果的橙色部分来自第一个查询而蓝色部分来自第二个查询,则无法保证。

因此,在查询末尾添加ORDER BY子句。您想要排序的属性尚不清楚。以下是一些可能性:

选项1:将相同的项目保持在一起,始终先是一个ID,然后是另一个。

...
ORDER BY i_item, i_id;

选项2:将相同的计数保持在一起,始终先是一个ID,然后是另一个

...
ORDER BY i_count, i_id;

选项3:在ID之间交替,从第一项开始,然后从第二项开始,......

ORDER BY row_number() over (partition by i_id order by i_item), i_id;