简体   繁体   English

使用T-SQL如何将以下行示例转换为列

[英]Using t-sql how to convert the below example of rows into columns

Entity          Description         Units   AssetId
Vehicle 100 A   Distance            8.48     2
Vehicle 100 A   Fuel                11       2
Vehicle 100 A   Parking             9        2
Vehicle 100 A   Tolls               10       2
Vehicle 1       Distance            8.48     5
Vehicle 1       Fuel                8        5
Vehicle 1       Parking             6        5
Vehicle 1       Tolls               7        5

Transform above dataset to: 将上述数据集转换为:

Vehicle Description     Distance    Fuel    Parking  Tolls  AssetId
Vehicle 100 A           8.48         11       9       10       2
Vehicle 1               8.48          8       6        7       5

A simple conditional aggregation may do the trick. 一个简单的条件聚合就可以解决问题。

Select [Vehicle Description] = Entity          
      ,Distance  = max(case when Description='Distance'  then Units else null end)
      ,Fuel      = max(case when Description='Fuel'      then Units else null end)
      ,Fuel      = max(case when Description='Parking'   then Units else null end)
      ,Tolls     = max(case when Description='Tolls'     then Units else null end)
      ,AssetId   = max(AssetID)
  From YourTable
  Group By Entity          

Using the PIVOT syntax you can do it this way: 使用PIVOT语法,您可以这样操作:

SELECT Entity [Vehicle Description],
   Distance,
   Fuel,
   Parking,
   Tolls,
   AssetId
FROM
(
SELECT Entity,
       Description,
       Units,
       Assetid
FROM yourtable) pt 
PIVOT(SUM(units) FOR description 
IN(Distance, Fuel, Parking, Tolls)) piv;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM