条件取决于条件的SUM子查询取决于父查询列,返回NULL

时间:2019-08-26 13:58:17

标签: mysql sql database

所有人!

我正在尝试计算每天的交易价格总和。我的工作:

SET @symbols_set = "A,B,C,D";

DROP TABLE IF EXISTS temp_deals;

CREATE TABLE temp_deals AS SELECT Deal, TimeMsc, Price, VolumeExt, Symbol FROM deals WHERE TimeMsc >= "2019-04-01" AND TimeMsc <= "2019-06-30" AND FIND_IN_SET(Symbol, @symbols_set) > 0;

SELECT
    DATE_FORMAT(TimeMsc, "%d/%m/%Y") AS Date,
    Symbol,
    (SELECT SUM(Price) FROM temp_deals dap WHERE dap.TimeMsc BETWEEN Date AND Date + INTERVAL 1 DAY AND dap.Symbol = Symbol) AS AvgPrice
FROM temp_deals
ORDER BY Date;

DROP TABLE IF EXISTS temp_deals;

但是结果是我在AvgPrice列中为NULL。我不明白我在做什么错。

看起来我无法将父查询的列传递给子查询,对吗?

1 个答案:

答案 0 :(得分:1)

限定您的列名。但大多数情况下,请勿使用字符串来比较日期:

SELECT DATE_FORMAT(d.TimeMsc, '%d/%m/%Y') AS Date,
       d.Symbol,
       (SELECT SUM(dap.Price)
        FROM temp_deals dap
        WHERE dap.TimeMsc >= d.TimeMsc AND
              dap.TimeMsc < d.TimeMsc + INTERVAL 2 DAY AND  -- not sure if you want 1 day or 2 day
              dap.Symbol = d.Symbol
       ) AS AvgPrice
FROM temp_deals d
ORDER BY d.TimeMsc;