2017-07-31 70 views
0

我有下面的SQL查詢,它返回以下用於員工時間ATTENDANCE的輸出。在SQL語句中選擇大小寫

注意當InOut = '0'它意味着,如果InOut = '1'它意味着。

查詢:

SELECT 
    DATEPART(mi, LogTime) AS [InMin], 
    OutletName as [InOutletName] 
FROM 
    [dbo].[AccessLog] 
INNER JOIN 
    dbo.Outlets ON dbo.Outlets.OutletCode = dbo.AccessLog.TerminalID 
WHERE 
    DATEPART(HOUR, LogTime) = '15' 
    AND InOut = '0' 
    AND CAST(LogDate AS date) = '2016-12-01' 

輸出:

InMin InOutletName 
-------------------- 
47  GJ-SH1 

我期待在獲得OutMin, OutOutletName的輸出,這可以應用在InOut = '1'

所需的輸出:

InMin InOutletName OutMin OutOutletName 
----------------------------------------- 
47  GJ-SH1  10  GJ-SH1 
+2

編輯你的問題,並提供樣本數據和期望結果。 –

+0

看起來你必須爲OutMin編寫另一個查詢(使用'InOut ='1''),並在'outletname'上加入兩個子查詢' –

回答

1

我沒有得到一個機會來嘗試,在我SSMS,但需要查詢應該是這樣的 -

SELECT 
    Case When InOut = '0' Then DATEPART(mi, LogTime) End AS [InMin], 
    Case When InOut = '0' Then OutletName End as [InOutletName], 
    Case When InOut = '1' Then DATEPART(mi, LogTime) End AS [OutMin], 
    Case When InOut = '1' Then OutletName End as [OutOutletName] 
FROM 
    [dbo].[AccessLog] 
INNER JOIN 
    dbo.Outlets ON dbo.Outlets.OutletCode = dbo.AccessLog.TerminalID 
WHERE 
    DATEPART(HOUR, LogTime) = '15' 
    AND CAST(LogDate AS date) = '2016-12-01'; 
0

一個簡單的解決辦法是加入AccessLog表兩次:

SELECT 
     DATEPART(mi, ali.LogTime) AS [InMin], 
     DATEPART(mi, alo.LogTime) AS [OutMin], 
     OutletName as [InOutletName] 
FROM dbo.Outlets 
INNER JOIN [dbo].[AccessLog] ali 
ON dbo.Outlets.OutletCode = ali.TerminalID 
LEFT JOIN [dbo].[AccessLog] alo 
ON dbo.Outlets.OutletCode = al0.TerminalID AND CAST(ali.LogDate AS date) = CAST(alo.LogDate AS date) AND alo.InOut = '1' 
WHERE DATEPART(HOUR, LogTime) = '15' 
AND ali.InOut = '0' 
AND CAST(ali.LogDate AS date) = '2016-12-01' 

注意,對於AccessLog代表我已經使用了left join的落伍,讓你也將獲得一個沒有記錄的出口名稱出來呢。

+0

謝謝,但我不想要找到「Outlet names hasn' t已註銷「 – Ayman

0

我剛剛在飛行中寫道,不確定結果,但你可以試試。它可以幫助:

;with InQuery as (SELECT 
    DATEPART(mi, LogTime) AS [InMin], 
    OutletName as [InOutletName] 
    FROM [dbo].[AccessLog] 
    INNER JOIN dbo.Outlets 
    ON dbo.Outlets.OutletCode = dbo.AccessLog.TerminalID 
    WHERE DATEPART(HOUR, LogTime) = '15' 
    AND InOut = '0' 
    AND CAST(LogDate AS date) = '2016-12-01'), 
    OutQuery As (SELECT 
    DATEPART(mi, LogTime) AS [OutMin], 
    OutletName as [OutOutletName] 
    FROM [dbo].[AccessLog] 
    INNER JOIN dbo.Outlets 
    ON dbo.Outlets.OutletCode = dbo.AccessLog.TerminalID 
    WHERE DATEPART(HOUR, LogTime) = '15' 
    AND InOut = '1' 
    AND CAST(LogDate AS date) = '2016-12-01') 

    select iq.*, oq.* from InQuery iq, OutQuery oq 
+0

消息156,級別15,狀態1,行4 關鍵字'FROM'附近的語法錯誤。 Msg 156,Level 15,State 1,Line 13 關鍵字'FROM'附近的語法不正確。 – Ayman

+0

現在請嘗試。我告訴過你,我寫得很快,所以一些逗號仍在那裏:) –

+0

嗨,感謝查詢沒有錯誤,但它返回空數據。 – Ayman