oracle order by:对称结果

时间:2016-12-02 11:05:19

标签: sql oracle sorting unpivot

电路有两个端点(支脚),每个支脚连接到设备。因此结果与每侧的电路对称,如A和B. 我希望按如下方式对SQL结果进行排序:

component location pathelement
-------------------------------
device_A    A       A_DD1
device_A    A       A_DD2
device_A    A       A_DD3
leg_A       L_A     A_LL1
leg_A       L_A     A_LL2
circuit     Center  CCCC
leg_B       L_B     B_LL1
leg_B       L_B     B_LL2
device_B    B       B_DD2
device_B    B       B_DD3

。 我的疑问是:

select component,location,pathelement,sortorder from 
(select c.name circuit,l.name leg,d.name d,
c.location c_loc,l_pe.location l_loc,d_pe.location d_loc,
c_pe.pathelements c_pe,l_pe.pathelements l_pe,d_pe.pathelements d_pe,
1 d_sortorder,2 l_sortorder,3 c_sortorder
from circuit c,leg l,device d,
(select circuitid,location,pathelements from circuit_details) c_pe,
(select legid,location,pathelements from leg_details)l_pe,
(select deviceid,location,pathelements from device_details)d_pe
where
c.circuit2leg=l.legid(+) 
and l.leg2device=d.deviceid(+)
and c.circuitid=c_pe.circuitid(+)
and l.legid=l_pe.legid(+)
and d.deviceid=d_pe.deviceid(+)
and c.name=<some_text>)
Unpivot((component,location,pathelement,sortorder) for c in 
((circuit,c_loc,c_pe,c_sortorder),(leg.l_loc,l_pe,l_sortorder),(device,d_loc,d_pe,d_sortorder))) order by sortorder;

实际输出为:

component location pathelement
-------------------------------
device_A    A       A_DD1
device_A    A       A_DD2
device_A    A       A_DD3
device_B    B       B_DD2
device_B    B       B_DD3
leg_A       L_A     A_LL1
leg_A       L_A     A_LL2
leg_B       L_B     B_LL1
leg_B       L_B     B_LL2
circuit     Center  CCCC

1 个答案:

答案 0 :(得分:0)

只需从表格中选择数据并将结果粘合在一起。如您事先知道所有可能的位置,您可以使用案例表达式来应用排序顺序。

select c.name, cd.location, cd.pathelement 
from circuit c 
join circuit_details cd on cd.circuitid = c.circuitid 
where c.name = <some_text>
UNION ALL
select l.name, ld.location, ld.pathelement 
from leg l 
join leg_details ld on ld.circuitid = l.circuitid 
where l.circuitid = (select c.circuitid from circuit c where c.name = <some_text>)
UNION ALL
select d.name, dd.location, dd.pathelement 
from device d 
join device_details dd on dd.circuitid = d.circuitid 
where d.circuitid = (select c.circuitid from circuit c where c.name = <some_text>)
ORDER BY 
  case location
    when 'A' then -2
    when 'L_A' then -1
    when 'Center' then 0
    when 'L_B' then 1
    when 'B' then 2
  end,
  pathelement;

最好是为五个位置及其排序键设置一个查找表。