在 MySQL 中使用临时 table 规范化数据

Normalize data using temporary table in MySQL

我有一个 table 的权重,我想在 MySQL 中重新归一化。当我尝试将它连接到依赖自身的内联查询时,出现“无法重新打开 table”错误,当我尝试使用 CTE 时,出现同样的错误。 Table 示例如下:

权重

monthEnd, portName, ticker, wgt
2019-04-30, test, MTUM, 0.20451060987312306
2019-04-30, test, SIZE, 0.20763723114425484
2019-04-30, test, USMV, 0.2043537465059284
2019-04-30, test, QUAL, 0.20758892877605561
2019-04-30, test, VLUE, 0.20683696239330326

我想做类似下面的事情来重新规范化 wgt 列(即 sum(wgt)=1):

select a.monthEnd, ticker, wgt/totWgt 
from weights a
inner join ( 
            select monthEnd, sum(wgt) as totWgt
            from weights
            group by monthEnd ) tot
            on a.monthEnd = tot.monthEnd

但我收到一条错误消息,指出:

Error Code: 1137. Can't reopen table: 'a'

我尝试使用 CTE 而不是临时 table 执行此操作时收到相同的消息,这似乎是 known issue within MySQL

只要我需要 weights table 来计算总重量,我尝试做的唯一可能的方法就是创建 另一个临时table来保存总重量并加入我的权重table以进行归一化。

在 MySQL 8.0.

中有没有更好的方法来做到这一点

MySQL 只允许您对临时 table 有一个引用。您可以 复制table。但是,window 函数是一个更简单的解决方案:

select monthEnd, ticker, wgt / sum(wgt) over (partition by monthEnd) 
from weights w