How to convert rows into columns in SQL Server?

后端 未结 2 1435
你的背包
你的背包 2021-01-06 20:49

I have this table from fingerprint sensor and I need to show the result in one row

ID |  DateTime                | Flag
-------------------------------------         


        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-06 21:08

    Simple aggregation should do:

    select id,
        max(case when flag = 'I' then datetime end) indatetime,
        max(case when flag = 'O' then datetime end) outdatetime
    from t
    group by id;
    

    Or If you want, you can use pivot:

    select id, [I] indatetime, [O] outdatetime
    from t pivot (
        max(datetime) for flag in ([I],[O])
    ) as p
    

提交回复
热议问题