看來,你只需要一個自聯接,從而獲得所需結果:
with table1(W_ID,S_ID,SEQ,Type) as (
select '1', 'Template1', 1, 'W' from dual union all
select '1', 'Template2', 2, 'W' from dual union all
select '1', '1', 3, 'S' from dual union all
select 'Template1', '2', 1, 'S' from dual union all
select 'Template1', '3', 2, 'S' from dual union all
select 'Template2', '4', 1, 'S' from dual union all
select 'Template2', '5', 2, 'S' from dual union all
select 'Template2', '6', 3, 'S' from dual)
----------
-- End if Data
----------
select a.S_ID a_s_id, b.s_id b_s_id, b.seq
from table1 a
join table1 b on a.s_id = b.w_id
where a.w_id = '1'
and (a.type='W' or a.w_id = b.s_id)
and b.type='S'
order by a.seq, b.s_id;
輸出:
| A_S_ID | B_S_ID | SEQ |
|-----------|--------|-----|
| Template1 | 2 | 1 |
| Template1 | 3 | 2 |
| Template2 | 4 | 1 |
| Template2 | 5 | 2 |
| Template2 | 6 | 3 |
| 1 | 1 | 3 |
更新:
改變序列還後,它工作正常(從評論部分: - >「改變S_ID的序列= 1〜2,使模板2的順序爲3,那麼結果應該是模板1的記錄然後再模板2的記錄以這種方式)S_ID 1的記錄
with table1(W_ID,S_ID,SEQ,Type) as (
select '1', 'Template1', 1, 'W' from dual union all
select '1', 'Template2', 3, 'W' from dual union all
select '1', '1', 2, 'S' from dual union all
select 'Template1', '2', 1, 'S' from dual union all
select 'Template1', '3', 2, 'S' from dual union all
select 'Template2', '4', 1, 'S' from dual union all
select 'Template2', '5', 2, 'S' from dual union all
select 'Template2', '6', 3, 'S' from dual)
----------
-- End if Data
----------
select a.S_ID a_s_id, b.s_id b_s_id, b.seq
from table1 a
join table1 b on a.s_id = b.w_id
where a.w_id = '1'
and (a.type='W' or a.w_id = b.s_id)
and b.type='S'
order by a.seq, b.s_id;
輸出:
| A_S_ID | B_S_ID | SEQ |
|-----------|--------|-----|
| Template1 | 2 | 1 |
| Template1 | 3 | 2 |
| 1 | 1 | 2 |
| Template2 | 4 | 1 |
| Template2 | 5 | 2 |
| Template2 | 6 | 3 |
有人懷疑列在某種程度上是相互關聯的。你能更好地解釋桌子的佈局嗎? – 2014-09-04 11:15:35
是的,在table1中,W_ID可以讓模板分配給它作爲S_ID,在這種情況下它的類型是W. W_ID也可以有直接的S_ID,在這裏它的類型是S.如果類型是W,那麼S_ID必須有擴展。意味着模板可以進一步將S_ID賦值給它,其類型爲S.現在我想要按SEQ順序獲得S_ID。 Template1的SEQ爲1,因此它的記錄將首先獲取,Template2的SEQ爲2,因此它的記錄將在稍後獲取。 – user3705792 2014-09-04 11:23:56