如何更改SQL查询,以便将不同的列值用作列名

时间:2016-05-02 23:57:12

标签: sql-server

我有以下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.

顺便说一句,可以使用以下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

1 个答案:

答案 0 :(得分:0)

这应该在报表应用程序(如SQL Server Reporting Services(SSRS))中完成。有关您的信息,将行数据转换为分组列的操作称为 pivoting ,虽然SQL Server确实进行了旋转,但它无法根据结果集中的唯一值进行自动旋转,除非你使用动态SQL自己做所有繁重的工作。

另一个选项是Microsoft Access。

不要试图将SQL Server转变为UI级别的报告平台。使用专为此工作设计的工具。