2016-05-02 37 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级别的报告平台。使用为工作而设计的工具。

相关问题