如何将Row值转换为包含字符串值的列?

时间:2014-11-27 05:22:31

标签: sql sql-server

这是我的表名TABLE1

ID |    ColumnName        |  ColumnValue
----------------------------------- 
48 |    VehicleNo         |  ABC-0134
48 |    In-Time           |  10:00
48 |    Out-Time          |  11:00

我想要结果如下:

ID  | VehicleNo  | In-Time |  Out-Time

48  | ABC-0134   | 10:00   |  11:00

请帮助我获得理想的结果。

2 个答案:

答案 0 :(得分:0)

您可以使用pivot,条件聚合或联接来执行此操作。这是一种方法:

select max(case when ColumnName = 'VehicleNo' then ColumnValue end) as VehicleNo,
       max(case when ColumnName = 'In-Time' then ColumnValue end) as InTime,
       max(case when ColumnName = 'Out-Time' then ColumnValue end) as OutTime
from table1
group by id;

答案 1 :(得分:0)

一种方法是使用Pivot

SELECT [ID], [VehicleNo],
       [In-Time],
       [Out-Time]
FROM   (SELECT id,
               ColumnName,
               ColumnValue
        FROM   tablename) a
       PIVOT (Max(columnvalue)
             FOR coulnname IN([VehicleNo],
                              [In-Time],
                              [Out-Time])) piv