SQL行到列的转置

时间:2013-03-01 14:21:57

标签: sql pivot

我在将列转换为行时遇到问题,透视似乎没有以我想要显示的方式给我结果。

以下是具有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

1 个答案:

答案 0 :(得分:1)

这是您想要做的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