[英]Partition by multiple columns written in rows from another table
假設我有這張桌子:
+------+-------+-------+-------+-------+--------+
| 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
可能嗎? 有人有更好的選擇嗎? 提前致謝!
這是你想要的嗎?
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.