【问题标题】:Using created variable in WHERE (MySQL)在 WHERE (MySQL) 中使用创建的变量
【发布时间】:2021-05-30 00:23:19
【问题描述】:

我在 MySQL 中有一张银行交易表,如下所示:

User ID Date Created Currency Amount USD_amt
1 April 1 USD 1000 1000
1 May 2 GBP 100 141.90
2 April 2 USD 50 50
2 May 5 EUR 200 243.85

USD_amt 是来自其他两个表的计算字段。我想按用户 ID 获得平均美元金额以及按用户 ID 按月平均金额,然后过滤月平均为用户平均 10 倍的行

现在,我正在尝试以下方法

SELECT
    t.user_id,
    t.created_date,
    month(t.created_date),
    year(t.created_date),
    (t.AMOUNT * fx.rate / POWER(10, cd.exponent)) USD_amt,
    avg(t.AMOUNT * fx.rate / POWER(10, cd.exponent)) monthly_avg,
    avg(t.AMOUNT * fx.rate / POWER(10, cd.exponent)) over (partition by t.user_id) user_avg
from
    transactions t
    join fx_rates fx
    on (fx.ccy = t.currency and fx.base_ccy = 'USD')
    join currency_details cd
    on cd.currency = t.currency
where
    monthly_avg > 10* user_avg
group by
    t.user_id,
    t.created_date,
    month(t.created_date),
    year(t.created_date)

虽然,我似乎无法在 WHERE 函数中使用创建的变量。

有什么想法吗?

【问题讨论】:

    标签: mysql where-clause


    【解决方案1】:

    您不能在 WHERE 子句中使用结果进行查询,因为在计算结果之前执行 WHERE。

    如果你想根据结果应用过滤器,你需要使用HAVING,它在之后执行。

    当然这对性能有影响:WHERE 允许您检索结果的子集,而 HAVING 返回所有行然后过滤它们。

    这里有一个快速修复你应该可以工作的代码

    SELECT
        t.user_id,
        t.created_date,
        month(t.created_date),
        year(t.created_date),
        (t.AMOUNT * fx.rate / POWER(10, cd.exponent)) USD_amt,
        avg(t.AMOUNT * fx.rate / POWER(10, cd.exponent)) monthly_avg,
        avg(t.AMOUNT * fx.rate / POWER(10, cd.exponent)) over (partition by t.user_id) user_avg
    from
        transactions t
        join fx_rates fx
        on (fx.ccy = t.currency and fx.base_ccy = 'USD')
        join currency_details cd
        on cd.currency = t.currency
    group by
        t.user_id,
        t.created_date,
        month(t.created_date),
        year(t.created_date)
    having
        monthly_avg > 10* user_avg
    

    【讨论】:

    • 感谢安德里亚的回复!我添加了 HAVING 函数,但是,现在我似乎收到以下错误:错误代码:3594。在此上下文中,您不能使用包含窗口函数的表达式的别名“user_avg”。'
    猜你喜欢
    • 2020-05-02
    • 2017-07-21
    • 2014-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-04
    • 1970-01-01
    相关资源
    最近更新 更多