如何在sql server中使用sql包含相同的行?

时间:2015-07-10 03:59:03

标签: sql sql-server

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

我想要如下结果:

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 个答案:

答案 0 :(得分: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的问题。