2016-05-02 75 views
0

我已在SQL查詢以下如何更改SQL查詢,以便不同的列值作爲列名

SELECT TOP 1000 
     [NumeroDocumento] 
     ,[Nombre] 
     , cast(BIT.Fecha as Date) as 'Fecha Bitacora' 
     , abs([OPN].KmInicio - [OPN].KmFin) as 'Kms' 
    FROM [adm].[Tripulantes] as TRI 
    INNER JOIN bit.OperacionesNavegaciones as OPN on OPN.TripulanteId = TRI.Id 
    INNER JOIN bit.Bitacora as BIT on BIT.Id = OPN.BitacoraId 

這是產生以下輸出

Current SQL output

我需要改變該SQL使輸出更改爲此

enter image description here

正如你所看到的人的名字由行出現一次,日期字段被渲染爲每個不同的值

我一直在使用PIVOT試過一列,這我很新使用以下sintax

SELECT TOP 4 
     TRI.NumeroDocumento 
     ,[Nombre] 

     , cast(BIT.Fecha as Date) as 'Fecha Bitacora' 
     , abs([OPN].KmInicio - [OPN].KmFin) as 'Kms' 
    FROM [adm].[Tripulantes] as TRI 
INNER JOIN bit.OperacionesNavegaciones as OPN on OPN.TripulanteId = TRI.Id 
INNER JOIN bit.Bitacora as BIT on BIT.Id = OPN.BitacoraId 

     PIVOT 
    (
    max([OPN].KmInicio) for BIT.FECHA in ([2016-01-04], [2016-03-24],[2016-01-25],[2016-03-02]) 

) as bla 

但執行

Msg 8156, Level 16, State 1, Line 19 
The column 'Id' was specified multiple times for 'bla'. 
Msg 4104, Level 16, State 1, Line 5 
The multi-part identifier "TRI.NumeroDocumento" could not be bound. 
Msg 4104, Level 16, State 1, Line 8 
The multi-part identifier "BIT.Fecha" could not be bound. 
Msg 4104, Level 16, State 1, Line 9 
The multi-part identifier "OPN.KmInicio" could not be bound. 
Msg 4104, Level 16, State 1, Line 9 
The multi-part identifier "OPN.KmFin" could not be bound. 

當這些錯誤可以固定的方式使用下列si​​ntax

我得到這個錯誤
SELECT * 
FROM 
(
SELECT 
    TOP 1000 
     TRI.NumeroDocumento 
     ,[Nombre] 

     , cast(BIT.Fecha as Date) as 'Fecha Bitacora' 
     , abs([OPN].KmInicio - [OPN].KmFin) as Kms 
    FROM [adm].[Tripulantes] as TRI 

INNER JOIN bit.OperacionesNavegaciones as OPN on OPN.TripulanteId = TRI.Id 
INNER JOIN bit.Bitacora as BIT on BIT.Id = OPN.BitacoraId 
) src 
     PIVOT 
    (
    sum(src.Kms) for src.[Fecha Bitacora] in ([2016-01-04], [2016-03-24],[2016-01-25],[2016-03-02]) 

) as bla 
+0

使用'pivot'。簡單的教程是在這裏:http://sqlhints.com/2014/03/18/dynamic-pivot-in-sql-server/ –

+0

@AlexKudryashev我已經更新了我的問題與我試圖使用的PIVOT和錯誤我得到了 - 感謝教程鏈接 –

回答

0

這應該在報表應用程序中完成,例如SQL Server Reporting Services(SSRS)。對於您的信息,這種將行數據轉換爲分組列的操作稱爲,偏移,雖然SQL Server確實執行了旋轉操作,但它不能根據結果集中的唯一值自動旋轉,除非您完成所有繁重的操作使用動態SQL。

另一種選擇是Microsoft Access。

不要嘗試將SQL Server轉換爲UI級別的報告平臺。使用爲工作而設計的工具。

相關問題