我有一张桌子,它的结构很简单:
user_id,月,余额,balance_type
我希望每个用户每月显示选定的余额类型,即:
user_id,month,balance_1,balance_2,balance_3,balance_.
因此,根据数据:
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中,最好的解决方案是什么?
发布于 2009-02-19 09:07:05
如果这是一次性的要求,我可以建议一个黑客。在user_id和月份中使用多个self联接(您将需要与平衡类型一样多的连接)。
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....这个解决方案可能不是最好的,但就像一次黑客攻击一样具有魅力。
发布于 2009-02-19 09:11:45
如果您有固定数量的平衡类型,并且(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、month和user_id,那么您将需要使用pivot命令来为每个组添加余额,这两者都存在于Server和user_id中(仅11g)。比如说,你有balance_types 1,2,3,4
select * from balance_table pivot (select sum(balance) for balance_type IN (1,2,3,4))如果您不知道预先有多少balance_types,那么我认为动态生成的sql是唯一的方法,在这种情况下,您应该使用DBMS_SQL的DBMS_SQL PL/SQL包。
https://stackoverflow.com/questions/564450
复制相似问题