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
這是產生以下輸出
我需要改變該SQL使輸出更改爲此
正如你所看到的人的名字由行出現一次,日期字段被渲染爲每個不同的值
我一直在使用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.
當這些錯誤可以固定的方式使用下列sintax
我得到這個錯誤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
使用'pivot'。簡單的教程是在這裏:http://sqlhints.com/2014/03/18/dynamic-pivot-in-sql-server/ –
@AlexKudryashev我已經更新了我的問題與我試圖使用的PIVOT和錯誤我得到了 - 感謝教程鏈接 –