【发布时间】: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