2009-02-19 152 views
2

我有一个表,具有简单的结构:分割行数据的列

USER_ID,月,平衡,balance_type

我想显示每月选择平衡类型为每个用户那就是:

USER_ID,月,balance_1,balance_2,balance_3,平衡_...

所以从数据:

ROW user_id month balance balance_type  
1 5667 09 20   2068 
2 5667 08 23   2068 
3 5667 07 21   2068 
4 5667 06 19   2068 
5 5667 10 22   2068 
6 5667 09 20   2069 
7 5667 08 23   2069 
8 5667 06 19   2069 
9 5667 07 21   2069 
10 5667 10 22   2069 
11 5667 09 4199  2114 
12 5667 06 4329  2114 
13 5667 08 4365  2114  
14 5667 10 4172,88 2114  
15 5667 07 4000  2114  
16 5667 10 572,1  6062  
17 5667 08 598,44  6062  
18 5667 07 548,4  6062  
19 5667 06 593,51  6062  
20 5667 09 575,69  6062  

我会得到例如用于每月09:

user_id, month, balance_1, balance_2, balance_3, balance_4  
5667 09 20 20 4199 575,69 

,这是什么在SQL和/或PL/SQL的最佳解决方案?

+0

如果您正在使用11G看到PIVOT子句:http://download.oracle.com/docs/cd/B28359_01/server.111/b28313/analysis.htm#DWHSG0209如果使用9I或10g看到这一点:HTTP ://asktom.oracle.com/pls/asktom/f p = 100:11:0 :::: P11_QUESTION_ID:419593546543。 – Yas 2009-02-19 13:40:20

回答

1

如果这是一次性要求,我可以建议一个黑客。在user_id和month上使用多个自连接(您将需要与平衡类型一样多的连接)。

select a.user_id, a.month, a.balance balance_1, b.balance balance_2, c.balance balance_3... 
from mytable a, mytable b, mytable c.... 
where 
a.month = 9 and 
a.balance_type=1 and 
a.user_id = b.user_id and 
a.month = b.month and 
b.balance_type=2 and 
b.user_id = c.user_id and 
c.user_id = d.user_id and 
c.balance_type=3.... 

这种解决方案可能不是最好的,但像一次性黑客一样起到魅力的作用。

1

如果您拥有固定数量的余额类型并且(user_id,month,balance_type)是唯一元组,那么您可以为每种余额类型进行内联子查询。例如:

select user_id, month, 
(select balance from balance_table bt where bt.user_id = user_id and bt.month = month and bt.balance_type = '1'), 
(select balance from balance_table bt where bt.user_id = user_id and bt.month = month and bt.balance_type = '2') ..... 
from balance_table 

如果它能够为具有相同balance_type,一个月多行和user_id说明,那么你将要使用的转动命令加起来余额为一组,这都存在于SQL Server和Oracle (仅11g)。例如说,你有balance_types 1,2,3,4

select * from balance_table pivot (select sum(balance) for balance_type IN (1,2,3,4)) 

如果你不知道你已经事先,那么我想动态生成SQL是多少balance_types去的唯一办法,在这种情况下你应该使用例如Oracle的DBMS_SQL PL/SQL包。