簡體   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

將上述數據集轉換為:

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

一個簡單的條件聚合就可以解決問題。

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          

使用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