以下是從表中的示例中,我有選擇進入和退出記錄表中的每個條目
F_ID R_ID DATE Col_A Col_B Col_C
12 158 20161008 01 99 99
12 158 20161012 01 01 99
12 158 20161019 01 02 10
12 158 20161022 99 01 10
12 160 20161006 01 99 01
12 160 20161011 99 01 99
12 160 20161017 99 01 10
17 167 20161013 99 01 01
17 167 20161016 99 02 99
17 167 20161020 02 01 10
17 174 20161010 99 01 01
17 174 20161012 01 02 11
17 174 20161017 99 99 10
我想選擇這樣,我得到以下結果
F_ID R_ID DATE Col_A Col_B Col_C
12 158 20161008 01 01 99 - Entry record
12 158 20161022 99 01 10 - Exit Record
12 160 20161006 01 99 01 - Entry record
12 160 20161017 99 01 10 - Exit Record
17 167 20161013 99 01 01 - Entry record
17 167 20161020 02 01 10 - Exit Record
17 174 20161010 99 01 01 - Entry record
17 174 20161017 99 99 10 - Exit Record
For each F_ID, R_ID:
When Col_A or Col_B = '01' and Col_C <>'10' - **It is an entry record**
When Col_C = '10' - **It is an exit record**
邏輯這裏是
1. Select the earliest entry record
**and**
2. Select the latest exit record for each F_ID, R_ID
我想利用工會類似下面的...
Select * from tbl1 T
where
T.Col_C = '10' and
T.DATE = (select max(T2.DATE) from tbl1 T2
where
T2.Col_C = '10' and
T2.R_ID = T.R_ID
T2.F_ID = T.F_ID
)
union
Select * from tbl1 K
where
(K.Col_A = '01' or K.Col_B = '01') and
K.Col_C <> '10' and
K.DATE = (select min(K2.DATE) from tbl1 K2 where
(K2.Col_A = '01' or K2.Col_B = '01') and
K2.Col_C <> '10' and
K2.R_ID = K.R_ID
K2.F_ID = K.F_ID
)
但是像我這樣在同一張桌子上用自聯接做的聯合正在給我返回一個垃圾數據。
會發生什麼事'爲col_a <>「 01''和'Col_B <>'01''和'Col_C <>'10''?這不是入口,也不是退出記錄,那麼這是什麼?你只是跳過這樣的記錄? –
「垃圾數據」究竟意味着什麼?在我看來查詢看起來沒問題。 'ORDER BY'子句當然會有幫助。而'UNION'沒有多大意義,因爲沒有必要消除的重複;改用'UNION ALL'。 –
Col_A <>'01'和Col_B <>'01'和Col_C <>'10' - 這個條件仍然可以算作條目記錄 – Hemansh