由写入另一张表的行中的多列进行分区

时间:2018-06-27 01:30:42

标签: sql oracle

假设我有这张桌子:

+------+-------+-------+-------+-------+--------+
| User | Value | Rule1 | Rule2 | Rule3 | Rule4  |
+------+-------+-------+-------+-------+--------+
|    1 |    10 |    20 |    14 |    15 |     22 |
|    2 |     5 |    20 |     7 |     8 |     25 |
+------+-------+-------+-------+-------+--------+

我想按查询进行分区,就像这样:

SELECT sum(Value) OVER (PARTITION BY Rule1, Rule2)
FROM MY_TABLE

但是我不想写“ Rule1,Rule2”。我想读一张像这样的表

+----+-------+
| ID | Rules |
+----+-------+
|  1 | Rule1 |
|  1 | Rule2 |
|  2 | Rule1 |
|  2 | Rule2 |
|  2 | Rule3 |
|  3 | Rule2 |
|  3 | Rule3 |
|  3 | Rule4 |
+----+-------+

所以我可以这样写:

SELECT sum(Value) OVER (PARTITION BY "all rules separated by comma where ID = 1")
FROM MY_TABLE

有可能吗?有人有更好的选择吗? 预先感谢!

1 个答案:

答案 0 :(得分:0)

这是您想要的吗?

select t.*,
       sum(value) over 
           (partition by (case when exists (select 1 from tablelikethis tlt where tlt.id = 1 and tlt.rules = 'rule1') then t.rule1 end),
                         (case when exists (select 1 from tablelikethis tlt where tlt.id = 1 and tlt.rules = 'rule2') then t.rule2 end),
                         (case when exists (select 1 from tablelikethis tlt where tlt.id = 1 and tlt.rules = 'rule3') then t.rule3 end),
                         (case when exists (select 1 from tablelikethis tlt where tlt.id = 1 and tlt.rules = 'rule4') then t.rule4 end)
           )
from my_table t