我有一個包含 3 個維度的表 - A、B 和 C。我基本上想要這些維度的所有可能組合的值,并在不存在組合時將所有度量(M)填充為 0。
假設我有桌子-

如果我這樣做,我會得到 -
select a,b,c from sum(m) fact group by a,b,c

但我想要所有可能的組合,-

目前,我正在做一個像下面這樣的交叉連接,但是有沒有更快的方法來做到這一點(因為我的表有大約 1M 條記錄)?——
select * from (
select distinct f1.a, f2.b, f3.c
from fact f1
cross join fact f2
cross join fact f3 ) all
left join
( select a,b,c from sum(m) fact group by a,b,c) s
on all.a=s.a and all.b=s.b and all.c=s.c
uj5u.com熱心網友回復:
如果這是 Oracle 資料庫,那么這正是cube它的用途。
select a, b, c, sum(m)
from my_table
group by cube(a,b,c)
uj5u.com熱心網友回復:
MySQL:
GROUP BY a,b,c 將為表中存在的每個組合生成 1 行。
如果你想要所有可能的組合,你需要多構建 1(或 3)個表來列出所有可能的值,然后LEFT JOIN從它們中做一個。您可能還需要COALESCE(col, 0)轉NULLs成零。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/333659.html
