簡體   English   中英

SQL行到列轉置

[英]SQL row to column transposing

我在將列轉換為行時遇到問題,透視似乎沒有以我想要顯示的方式給我結果。

這是具有n行數的樣本數據模式:

Coulmn1      Column2
Customer     C1
Account      A1
Transaction  T1
Transaction  T2
Transaction  T3
Account      A2
Transaction  T11
Transaction  T12
Transaction  T13
Customer     C2
Account      A11
Transaction  T111
Transaction  T112
Transaction  T113
Account      A12
Transaction  T1111
Transaction  T1112
Transaction  T1113

我想將其轉置為以下格式

Customer  Account  Transaction
C1        A1       T1
C1        A1       T2
C1        A1       T3
C1        A2       T11
C1        A2       T12
C1        A2       T13
C2        A11      T111
C2        A11      T112
C2        A11      T113
C2        A12      T1111
C2        A12      T1112
C2        A12      T1113

這是您要執行的MySQL版本。 它使用相關的子查詢來獲取客戶和帳戶信息:

select t.Column1,
       (select column2 from t t2 where t2.column1 = 'Customer' and t2.id <= t.id order by t2.id desc limit 1
       ) as customer,
       (select column2 from t t2 where t2.column1 = 'Account' and t2.id <= t.id order by t2.id desc limit 1
       ) as transaction,
from t
where t.column1= 'Transaction'

假設您有一個ID列用於對行進行排序。 如果不是,那么您需要找出一種獲取此類列(id或時間戳)的方法,因為SQL表本質上是無序的。

在其他數據庫中,邏輯將類似。 但是,代替limit 1的語法可能是select top 1where rownum = 1fetch only 1 row

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM