2015-10-20 150 views
0

我有一個像這樣的臨時表。 enter image description here樞軸查詢SQL重複行

然後我使用以下查詢和附加的輸出來旋轉該表。

SELECT * 
FROM (
    SELECT * from @tmpTable2 
) AS SourceTable 
PIVOT 
(
max(timec) 
FOR eventb 
IN (
[Veh Reg Time],[Fitness ok time],[RFID Issue time],[MG-IN],[WB IN], 
[MG-OUT],  [WB OUT] 
) 
) AS PivotTableAlias 

enter image description here

在這裏的問題是一個 'REGNO' 有多個記錄。但是我只想要一行'RegNo'。 我該如何做到這一點?

預計應該是這樣的。 enter image description here

+1

我想'DISTINCT'會幫助你或'GROUP BY' – wiretext

+0

如何使用不同的此查詢? – Tom

+0

ok在此處發佈您的預期輸出結果 – wiretext

回答

1
SELECT * 
FROM (
    SELECT regno,eventb,timec,rfid from @tmpTable2 
) AS SourceTable 
PIVOT 
(
max(timec) 
FOR eventb 
IN (
[Veh Reg Time],[Fitness ok time],[RFID Issue time],[MG-IN],[WB IN], 
[MG-OUT],  [WB OUT] 
) 
) AS PivotTableAlias 
0
SELECT pt.regno, pt.rfid, MAX(vrt), MAX(fot), MAX(rit), MAX(MI), MAX(wi), MAX(Mo), MAX(wo) FROM (
SELECT * 
FROM (
    SELECT * from @temtable2 t 
) SourceTable 
PIVOT 
(
max(timec) 
FOR eventb 
IN('Veh Reg Time' AS vrt,'Ftness Ok time' AS fot, 'RFID Issue time' AS rit, 'MG-IN' AS mi, 'WB IN' AS wi, 'MG-OUT' AS mo, 'WB OUT' AS wo) 
) PivotTableAlias) pt 
GROUP BY pt.regno, pt.rfid