假設我問我在以前的評論是真實的,(只空或REF1和REF2每個名稱,DRCT對一個給定的值),這似乎工作:
select NAME, M_REF1, M_REF2, DRCT
from (
select A.NAME, coalesce(A.REF1, B.REF1) m_REF1,
coalesce(A.REF2, B.REF2) m_REF2, A.REF1 A_REF1, B.REF1 B_REF1,
A.REF2 A_REF2, B.REF2 B_REF2, A.DRCT
from Table1 A JOIN Table1 B on A.NAME = B.NAME AND A.DRCT = B.DRCT)
WHERE A_REF1 = m_REF1 AND B_REF2 = m_REF2
UNION
select A.NAME, A.REF1, A.REF2, A.DRCT
FROM Table1 A JOIN
(select NAME, DRCT, COUNT(*)
from Table1
group by NAME, DRCT
HAVING COUNT(*) = 1) B ON A.NAME = B.NAME AND A.DRCT = B.DRCT;
工會是因爲只有一個記錄的行不包含在第一個SELECT中。
但這是有點簡單,工程太:
select A.NAME, coalesce(A.REF1, B.REF1) M_REF1, coalesce(A.REF2,B.REF2) M_REF2,A.DRCT
from Table1 A LEFT OUTER JOIN Table1 B ON A.DRCT = B.DRCT AND A.NAME = B.NAME
WHERE NVL2(A.REF1,0,1) = 1 AND NVL2(B.REF1,0,1) =0
AND NVL2(A.REF2,0,1) = 0 AND NVL2(B.REF2,0,1) = 1
UNION
select A.NAME, A.REF1, A.REF2, A.DRCT
FROM Table1 A JOIN
(select NAME, DRCT, COUNT(*)
from Table1
group by NAME, DRCT
HAVING COUNT(*) = 1) B ON A.NAME = B.NAME AND A.DRCT = B.DRCT;
可以REF1和REF2採取一個給定的名稱和DRCT什麼樣的價值觀?以你爲例,對於NAME = A和DRCT = D1的記錄,REF1只能取(空)或Rb,或者REF1可能是Rx? – neutrino 2013-03-14 14:13:59
每個值都是允許的。但是每行只能定義一個列。如果ref1被定義,ref2將爲空。反之亦然。 – 2013-03-14 15:40:15
然後,我想我的答案會爲你工作。但我會以更簡單的方式去思考。 – neutrino 2013-03-14 16:18:12