SQL Query以水平格式从垂直格式获取详细信息

时间:2015-08-29 08:20:38

标签: sql-server



我创建了一张桌子。

-------------- | --------------- |
cust1 | cust2 |
-------------- | --------------- |
客户| C1 |
帐户| A1 |
交易| T1 |
交易| T2 |
交易| T3 |
帐户| A2 |
交易| T11 |
交易| T12 |
交易| T13 |
客户| C2 |
帐户| A1 |
交易| T111 |
交易| T112 |
交易| T113 |
帐户| A2 |
交易| T1111 |
交易| T1112 |
交易| T1113 |
-------------- | --------------- |

请帮我构建SQL查询以获得以下格式的结果:

---------------------- | ------------------- | ---- ----------------- |
客户|帐户|交易|
---------------------- | ------------------- | ------- -------------- |
C1 | A1 | T1 |
C1 | A1 | T2 |
C1 | A1 | T3 |
C1 | A2 | T11 |
C1 | A2 | T12 |
C1 | A2 | T13 |
C2 | A1 | T111 |
C2 | A1 | T112 |
C2 | A1 | T113 |
C2 | A2 | T1111 |
C2 | A2 | T1112 |
C2 | A2 | T1113 |
---------------------- | ------------------- | ------- -------------- |

由于

1 个答案:

答案 0 :(得分:0)

您需要对数据进行某种排序,因此如果您将名称字段添加到名为id的表中以跟踪数据的顺序,则可以执行此操作:

select c.cust2, a.cust2, t.cust2
from table1 t
outer apply (
  select top 1 cust2, id from table1 t1
  where t1.id < t.id and cust1 = 'customer' 
  order by id desc
) c
outer apply (
  select top 1 cust2, id from table1 t1
  where t1.id < t.id and cust1 = 'account' 
  order by id desc
) a
where cust1 = 'transaction'

SQL Fiddle

中的示例

编辑:这可以在不更改表的情况下工作,但可以随时中断。

;with Table1 as (
  select row_number() over (order by (select null)) as id,*
  from table2                            
)

select c.cust2, a.cust2, t.cust2
from table1 t
outer apply (
  select top 1 cust2, id from table1 t1
  where t1.id < t.id and cust1 = 'customer' 
  order by id desc
) c
outer apply (
  select top 1 cust2, id from table1 t1
  where t1.id < t.id and cust1 = 'account' 
  order by id desc
) a
where cust1 = 'transaction'