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和错误我得到了 - 感谢教程链接 –