2016-08-03 98 views
0

請問如何從這些數據中獲得如下結果?SQL連接結合條件

(我想合併的條件,但仍然有一些不必要的行加入。)

輸入是在只有一個表:

ID IN OUT 
----------------- 
1 6:00 null 
2 7:11 null 
2 null 16:30 
3 null 19:00 

輸出(視圖)應結合相同ID,這樣的結果是這樣的:

ID IN OUT 
------------------ 
1  6:00 null 
2  7:11 16:30 
3  null 19:00 
+0

可以有超過2相同的ID? – gh9

+0

謝謝,解決方案由兩個步驟組成: 1.標準化數據 - 將它們分成三個不同的視圖(僅IN,僅限OUT和組合IN和OUT) 2.聯合所有這3個視圖分爲4h一個 –

回答

0

你可以嘗試用一個CTE來實現這一目標如下:

CREATE TABLE #data 
(
    Id int not null, 
    inTime varchar(10) null, 
    outTime varchar(10) null 
) 

INSERT INTO #data VALUES 
    (1, '6:00', null), 
    (2 , '7:11', null), 
    (2 , null, '16:30'), 
    (3 , null, '19:00') 


WITH combinedTable AS (
    SELECT 
    Id, 
    MAX(inTime) AS A, 
    MAX(outTime) AS B 
FROM #data 
GROUP BY Id 
HAVING MAX(2) = MIN(2) 
    AND MAX(3) = MIN(3) 
) 
    SELECT * 
    FROM combinedTable 
    UNION ALL 
    SELECT * 
    FROM #data 
    WHERE ID NOT IN (SELECT ID FROM combinedTable) 
0

以下可達到目的: 1.有一個表ID和在IN不等於空值:

(select ID, IN from table where In ne NULL()) as tableA 

O/P將是:

ID IN  
1 6:00 
2 7:11 

2 。具有ID和OUT的表,其中OUT不等於空:

(select ID, OUT from table where OUT ne NULL()) as tableB 

O/P將是:

ID OUT 
2 16:30 
3 19:00 

3.Outer加入兩個表:

select tableA.ID,tableA.IN, tableB.OUT 
from table as tableA 

outer full join 

select ID,OUT from table as tableB 
On tableA.ID=tableB.ID and tableA.IN ne Null() and tableB.OUT ne NULL() 

輸出將所需的輸出:

ID IN OUT 
1  6:00 null 
2  7:11 16:30 
3  null 19:00