2017-05-04 47 views
0

新手問題:SQL:PIVOT與加盟

我見下表

Period Customer Balance 
40  1  10 
40  2  15 
39  1  9 
38  1  10 
38  2  20 

我想訂購它,這樣我每個時期一列,

Customer BalancePeriod38 BalancePeriod39 BalancePeriod40 
1    10    9    10 
2    15    .    20 

是這可能嗎?

+0

其所謂的支點。在每個RDBMS上都有數以百萬計的關於它的帖子。 – dfundako

回答

1

您可以使用聚合與案件數據:

select customer, 
    sum(case when period = 38 then balance else 0 end) as balance_period_38, 
    sum(case when period = 39 then balance else 0 end) as balance_period_39, 
    sum(case when period = 40 then balance else 0 end) as balance_period_40 
from your_table 
group by customer;