你的想法是正确的,你需要首先unpivot
才能得到你想要的最终结果。您需要将Billings
,Collections
和Debtors
的多个列转换为多个行,然后将Period
值转换为列。
你没有指定你使用的是什么版本的SQL Server,但是在SQL Server 2005开始,您可以使用CROSS APPLY
到UNPIVOT:
select
CompanyCode,
AccountClass,
period,
[Type],
Value
from yourtable t
cross apply
(
select 'Billings', Billings union all
select 'Collections', Collections union all
select 'Debtors', Debtors
) c ([Type], value);
见Demo。这将您的数据转换成格式:
| COMPANYCODE | ACCOUNTCLASS | PERIOD | TYPE | VALUE |
|-------------|----------------------|--------|-------------|-------|
| 500 | Accounts Receiveable | 1 | Billings | xx |
| 500 | Accounts Receiveable | 1 | Collections | xx |
| 500 | Accounts Receiveable | 1 | Debtors | xx |
| 500 | Accounts Receiveable | 2 | Billings | xxx |
| 500 | Accounts Receiveable | 2 | Collections | xx |
你会发现,你现在必须为每个Billings
,Collections
和Debtors
一行。现在,您可以将旋转功能的Period
列:
select
CompanyCode,
AccountClass,
Type,
[1],
[2],
[3]
from
(
select
CompanyCode,
AccountClass,
period,
[Type],
Value
from yourtable t
cross apply
(
select 'Billings', Billings union all
select 'Collections', Collections union all
select 'Debtors', Debtors
) c ([Type], value)
) unp
pivot
(
max(value)
for period in ([1], [2], [3])
) piv;
见SQL Fiddle with Demo。这给你一个结果:
| COMPANYCODE | ACCOUNTCLASS | TYPE | 1 | 2 | 3 |
|-------------|----------------------|-------------|----|-----|-----|
| 500 | Accounts Receiveable | Billings | xx | xxx | xx |
| 500 | Accounts Receiveable | Collections | xx | xx | xx |
| 500 | Accounts Receiveable | Debtors | xx | xx | xxx |
现在,如果你有在CompanyCode
和AccountClass
可能出现多次为同一Period
的可能性,你需要创建一个可以用来返回多个不同的值行。在这种情况下,您需要使用类似于row_number()
的窗口函数来为这些组合创建唯一序列。我会稍微修改上面的代码:
select
CompanyCode,
AccountClass,
Type,
[1],
[2],
[3]
from
(
select
CompanyCode,
AccountClass,
seq,
period,
[Type],
Value
from
(
select CompanyCode, AccountClass, Period, Billings,
Collections, Debtors,
seq = row_number() over(partition by CompanyCode, AccountClass, Period
order by CompanyCode, AccountClass)
from yourtable
) t
cross apply
(
select 'Billings', Billings union all
select 'Collections', Collections union all
select 'Debtors', Debtors
) c ([Type], value)
) unp
pivot
(
max(value)
for period in ([1], [2], [3])
) piv;
请参阅SQL Fiddle with Demo。您会注意到这会将结果略微更改为:
| COMPANYCODE | ACCOUNTCLASS | TYPE | 1 | 2 | 3 |
|-------------|----------------------|-------------|----|--------|--------|
| 500 | Accounts Receiveable | Billings | xx | xxx | xx |
| 500 | Accounts Receiveable | Collections | xx | xx | xx |
| 500 | Accounts Receiveable | Debtors | xx | xx | xxx |
| 500 | Accounts Receiveable | Billings | xx | (null) | (null) |
| 500 | Accounts Receiveable | Collections | xx | (null) | (null) |
| 500 | Accounts Receiveable | Debtors | xx | (null) | (null) |
@Bluefeet:PIVOT的问题! :-) – 2014-09-02 16:52:09
@marc_s你响了? :) – Taryn 2014-09-02 17:17:01