我有一个按ID1排序的表A: id1 id2
1 8
1 9
3 5
3 7
6 7
7 9
但我希望得到这个:
id1 id2
1 8
1 9
7 9
3 5
3 7
6 7
首先应该是id1的相等值,此后应该是id2的等值,依此类推
答案 0 :(得分:3)
我认为这应该可以解决问题:
SELECT id1, id2
FROM table
ORDER BY (CASE WHEN id1 < id2 THEN id1 ELSE id2 END), id1, id2;
CASE WHEN id1 < id2 THEN id1 ELSE id2 END
用于获取两个ID中的最低者(感谢@dnouth),您可以对此进行排序。
请参阅 this SQL Fiddle 以获取示例。
如果您使用Oracle,则可以尝试以下操作:
SELECT id1, id2
FROM table
ORDER BY LEAST(id1, id2), id1, id2;
请参阅 this SQL Fiddle 。
答案 1 :(得分:1)
如果星号表示与前一行中的值有连接,那么这将适用于您的样本数据:
Oracle查询:
SELECT id1, id2
FROM (
SELECT id1, id2, ROWNUM rn
FROM (
SELECT *
FROM (
SELECT *
FROM table_name
ORDER BY id1, id2
)
CONNECT BY NOCYCLE
( PRIOR id1 = id1 AND PRIOR id2 < id2 )
OR ( PRIOR id1 < id1 AND PRIOR id2 = id2 )
ORDER SIBLINGS BY id1, id2
)
)
GROUP BY id1, id2
ORDER BY MIN( rn );
<强>结果:
ID1 | ID2
-----------
1 | 2
1 | 3
7 | 3
2 | 4
2 | 5
6 | 5
4 | 7
<强>更新强>:
Oracle查询:
SELECT id1,
id2,
DENSE_RANK() OVER ( ORDER BY grp_id ) AS grp_id
FROM (
SELECT id1,
id2,
grp_id,
ROW_NUMBER() OVER ( PARTITION BY id1, id2 ORDER BY rn ) AS first_row
FROM (
SELECT id1,
id2,
grp_id,
ROWNUM AS rn
FROM (
SELECT id1,
id2,
CONNECT_BY_ROOT( rn ) AS grp_id
FROM (
SELECT id1,
id2,
ROWNUM AS rn
FROM (
SELECT id1,
id2
FROM table_name
ORDER BY id1, id2
)
)
CONNECT BY NOCYCLE
( PRIOR id1 = id1 AND PRIOR id2 < id2 )
OR ( PRIOR id1 < id1 AND PRIOR id2 = id2 )
ORDER SIBLINGS BY id1, id2
)
)
ORDER BY rn
)
WHERE first_row = 1;
<强>结果:
ID1 | ID2 | GRP_ID
--------------------
1 | 2 | 1
1 | 3 | 1
7 | 3 | 1
2 | 4 | 2
2 | 5 | 2
6 | 5 | 2
4 | 7 | 3
答案 2 :(得分:0)