Разделение на несколько столбцов, записанных в строках из другой таблицы - PullRequest
0 голосов
/ 27 июня 2018

Допустим, у меня есть эта таблица:

+------+-------+-------+-------+-------+--------+
| 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 голосов
/ 27 июня 2018

Это то, что вы хотите?

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 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...