2015-07-10 48 views
-1
 
NIK  IN/OUT    DATE 
10026 1  2015-07-07 14:15:09.000 
10026 0  2015-07-06 14:16:28.000 
10026 1  2015-07-06 14:16:37.000 
10026 0  2015-07-08 05:26:17.000

我想要的結果如下圖所示:如何在sql server中使用sql的相同行?

 
NIK  DATE IN      DATE OUT 
10026 2015-07-07 14:15:09.000  null 
10026 2015-07-06 14:16:28.000 2015-07-06 14:16:37.000 
10026 null      2015-07-08 05:26:17.000

如何將在SQL Server中使用SQL基於實地同一行(IN-OUT)?

+1

爲什麼'2015-07-06 14:16:37.000'有1並記錄爲Date OUT,但'2015-07-07 14:15:09.000'也有1並記錄爲Date IN?你爲什麼把它標記爲MySQL? – cha

+0

同意@cha –

回答

0
Set Nocount On; 

Declare @test Table 
(
    NIK   Int 
    ,InOut   Bit 
    ,Date   Datetime 
) 

Insert Into @test(NIK,InOut,Date) Values 
(10026,1,'2015-07-07 14:15:09.000') 
,(10026,0,'2015-07-06 14:16:28.000') 
,(10026,1,'2015-07-06 14:16:37.000') 
,(10026,0,'2015-07-08 05:26:17.000') 


Select t.NIK,[0] As DateIn,[1] As DateOut 
From (
      Select t.NIK 
        ,t.InOut 
        ,Max(t.Date) As Date 
        ,Dateadd(D, 0, Datediff(D, 0, t.Date)) As OnlyDate 
      From @test As t 
      Group BY Dateadd(D, 0, Datediff(D, 0, t.Date)) 
        ,t.NIK 
        ,t.InOut 
     ) As t 
     PIVOT 
     (
      Min(t.Date) 
      For InOut In ([0],[1]) 
     ) As t 

輸出: -

enter image description here

我認爲,有可能是與你的數據0/1一個問題。

+0

爲什麼你認爲每天只有一種進出組合? – cha

+0

即使不是,那麼也需要將Min DateIn和Max Dateout作爲特定的Date和NIK,然後需要產生樞軸。但是如果最終用戶想要顯示整天的內容,那麼上面的查詢將不起作用。但是這樣的要求應該被提及。 –

相關問題