【发布时间】:2017-06-13 05:47:09
【问题描述】:
我的情况几乎与以下线程中讨论的示例相同。
select data where date is max(date) less than x
我有表格
s_currency
cdate ratio currency
-------------------------------------------------------------------
2017-06-06 00:00:00.0 1 USD
2017-06-05 00:00:00.0 1 USD
2017-06-04 00:00:00.0 1 USD
s_transaction
tdate amount currency
-------------------------------------------------------------------
2017-06-05 00:00:00.0 100 USD
2017-06-08 00:00:00.0 55 USD
2017-06-08 00:00:00.0 55 USD
2017-06-08 00:00:00.0 60 USD
而我想要的结果是
tdate amount currency ratio cdate
--------------------------------------------------------------------------
2017-06-05 00:00:00.0 100 USD 1 2017-06-05 00:00:00.0
2017-06-08 00:00:00.0 55 USD 1 2017-06-06 00:00:00.0
2017-06-08 00:00:00.0 55 USD 1 2017-06-06 00:00:00.0
2017-06-08 00:00:00.0 60 USD 1 2017-06-06 00:00:00.0
cdate 应基于 tdate,即其最新的货币日期等于或早于交易日期。
另一篇文章中的解决方案在 select 子句中使用了子查询,它在 Impala 中不起作用。我尝试使用 CTE 并加入子查询,但它们都没有返回所需的结果。以下是我构建的一些查询及其结果
SELECT tdate, amount, t1.currency, ratio, cdate FROM s_transaction t1 , s_currency t2
WHERE t1.currency = t2.currency AND
t2.cdate = (select max(cdate) from s_currency
where currency = t1.currency and cdate <= t1.tdate);
但这会加入表格并返回所有货币的交易,小于交易日期,所以我得到
tdate amount currency ratio cdate
------------------------------------------------------------------------------------------
2017-06-08 00:00:00.0 60 USD 1 2017-06-05 00:00:00.0
2017-06-08 00:00:00.0 60 USD 1 2017-06-06 00:00:00.0
2017-06-08 00:00:00.0 60 USD 1 2017-06-04 00:00:00.0
2017-06-05 00:00:00.0 100 USD 1 2017-06-05 00:00:00.0
2017-06-05 00:00:00.0 100 USD 1 2017-06-04 00:00:00.0
2017-06-08 00:00:00.0 55 USD 1 2017-06-05 00:00:00.0
2017-06-08 00:00:00.0 55 USD 1 2017-06-06 00:00:00.0
2017-06-08 00:00:00.0 55 USD 1 2017-06-04 00:00:00.0
2017-06-08 00:00:00.0 55 USD 1 2017-06-05 00:00:00.0
2017-06-08 00:00:00.0 55 USD 1 2017-06-06 00:00:00.0
2017-06-08 00:00:00.0 55 USD 1 2017-06-04 00:00:00.0
所以,我摆脱了 max(cdate) 并使用限制为 1 的 order by,但 Impala 抛出了一个错误,即它的 Unsupportedrelated subquery with a LIMIT 子句。
我尝试使用 CTE 并写了
with lastupdate as (
select t2.currency, ratio, max(cdate) as cdate from s_currency t2 join s_transaction t1
on cdate <= tdate and t2.currency = t1.currency group by t2.currency, ratio limit 1
) select t11.*, lst.ratio, lst.cdate
from s_transaction t11 join lastupdate lst
但这里 CTE 选择一个值并将其用于所有交易,所以我得到了
tdate amount currency ratio cdate
-------------------------------------------------------------------------------------------
2017-06-05 00:00:00.0 100 USD 1 2017-06-06 00:00:00.0
2017-06-08 00:00:00.0 55 USD 1 2017-06-06 00:00:00.0
2017-06-08 00:00:00.0 60 USD 1 2017-06-06 00:00:00.0
2017-06-08 00:00:00.0 55 USD 1 2017-06-06 00:00:00.0
6 月 5 日的交易,其 cdate 应为 6 月 5 日。
我什至尝试在子查询中使用 row_number() 函数,但它无法解析 t1.tdate 来比较日期的值。
我怎样才能达到我想要的?
【问题讨论】:
标签: sql common-table-expression impala row-number correlated-subquery