在“超级行”之后对行进行分组

时间:2014-09-08 16:00:51

标签: sql oracle grouping

我有这张桌子:

+-------------+-----------------------+----------------------+
| supplier_id | supplier_aggregate_id | supplier_description |
+-------------+-----------------------+----------------------+
| &&%%        | null                  | UNDEFINED            |
| ...         | &&%%                  | UNDEFINED            |
| +           | null                  | UNDEFINED            |
| ,           | &&%%                  | UNDEFINED            |
| .           | &&%%                  | UNDEFINED            |
+-------------+-----------------------+----------------------+

我想选择以这种方式获得结果:

+-------------+-----------------------+----------------------+
| supplier_id | supplier_aggregate_id | supplier_description |
+-------------+-----------------------+----------------------+
| &&%%        | null                  | UNDEFINED            |
| ,           | &&%%                  | UNDEFINED            |
| .           | &&%%                  | UNDEFINED            |
| ...         | &&%%                  | UNDEFINED            |
| +           | null                  | UNDEFINED            |
+-------------+-----------------------+----------------------+

即:一行supplier_id,后面是supplier_aggregate_id等于第一行supplier_id的所有行。

我尝试了订购:

SELECT supplier_id, supplier_aggregate_id, supplier_description
FROM suppliers
ORDER BY supplier_id ASC, supplier_aggregate_id ASC;

但是我在第一个+记录后得到&&%%记录,这是不正确的:

+-------------+-----------------------+----------------------+
| supplier_id | supplier_aggregate_id | supplier_description |
+-------------+-----------------------+----------------------+
| &&%%        | null                  | UNDEFINED            |
| +           | null                  | UNDEFINED            | <-- this should be here
| ,           | &&%%                  | UNDEFINED            |                      |
| .           | &&%%                  | UNDEFINED            |                      |
| ...         | &&%%                  | UNDEFINED            |                      |
+-------------+-----------------------+----------------------+ <--------------------+

有没有办法通过单个查询来实现这一目标?

SQLFiddle

1 个答案:

答案 0 :(得分:2)

最简单的事情似乎是:

select 
  s.supplier_id, 
  s.supplier_aggregate_id, 
  s.supplier_description 
from suppliers s
order by 
  COALESCE(s.supplier_aggregate_id, s.supplier_id) asc, 
  s.supplier_aggregate_id;

http://sqlfiddle.com/#!2/67cae/21