努力与此子查询-它应该是基本的,但我缺少一些东西。我需要将它们作为较大查询的一部分提供。
我有客户,我想获得时间戳最高的一笔交易。
顾客
customer foo
1 val1
2 val2
交易
tx_key customer timestamp value
1 1 11/22 10
2 1 11/23 15
3 2 11/24 20
4 2 11/25 25
查询的理想条件:
customer foo timestamp value
1 val1 11/23 15
2 val2 11/25 25
我成功编写了一个子查询,以通过使用多个子查询来计算所需的内容,但是当我拥有较大的数据集时,它非常慢。
我这样做是这样的:
(select timestamp where transaction.customer = customer.customer order by timestamp desc limit 1) as tx_timestamp
(select value where transaction.customer = customer.customer order by timestamp desc limit 1) as tx_value
那么,如何将其简化为仅计算一次呢?在我的真实数据集中,我有15列连接超过10万行,因此,一遍又一遍地执行此操作还不够高效。
请尝试以下查询:
SELECT
T.customer, T.foo, T.timestamp, T.value
FROM Transaction T
JOIN
(SELECT
customer, max(timestamp) as timestamp
from Transaction GROUP BY customer) MT ON
T.customer = MT.customer
AND t.timestamp = MT.timestamp
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句