2017-02-22 72 views
2

我從指紋傳感器這個表,我需要顯示在一排如何將行轉換爲SQL Server中的列?

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 

誰能幫助我?

回答

4

簡單聚合應該做的:

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; 

,或者如果你願意,你可以使用透視:

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

非常感謝。現在它正在工作。 –

2

另外,您可以使用PIVOT,已開發出專門把ROWSCOLUMNS

SELECT id 
    , [I] as [IN-DateTime] 
    , [O] as [OUT-DateTime] 
FROM Table t 
PIVOT (max(dateTime) for flag in ([I], [O])) as pvt;