如何将行转换为SQL Server中的列?

时间:2017-02-22 16:17:00

标签: sql-server sql-server-2008 sql-server-2012

我有来自指纹传感器的这张表,我需要在一行中显示结果

ID |  DateTime                | Flag
----------------------------------------
41 |  2017-02-22 08:05:56.000 | I
41 |  2017-02-22 18:11:03.000 | O

结果需要这样:

ID |  IN-DateTime             |  OUT-DateTime           
--------------------------------------------------------
41 |  2017-02-22 08:05:56.000 | 2017-02-22 18:11:03.000 

任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:7)

简单聚合应该:

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;

或者如果需要,可以使用pivot:

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

答案 1 :(得分:2)

或者,您可以使用PIVOT,该ROWS专门用于将COLUMNS转换为SELECT id , [I] as [IN-DateTime] , [O] as [OUT-DateTime] FROM Table t PIVOT (max(dateTime) for flag in ([I], [O])) as pvt;

<link rel="stylesheet" type="text/css" href="/CSS/style.css">