根据每个用户的不同值过滤值
Filtering values according to a different value for each user
我正在尝试了解如何在 mySQL 中执行我通常在 python 中执行的操作。
我有一个销售额 table,列为 sale_date、user_id 和 price_USD。每行都是用户下的订单。
我想要一个新的 table,其中包含所有比用户最后一次下订单花费更多的订单(所以在这张图片中,只有黄色行)。
我知道如何获取每个用户的最后订单的 table,但我无法将其保存在数据库中。
我如何通过 user_id 将每一行的价格与不同的值进行比较,并在一个 'swoop' 中获得较大的价格?
谢谢
如果您是 运行 MysL 8.0,您可以使用 window 函数来完成此操作:
select t.*
from (
select
t.*,
first_value(price_usd)
over(partition by user_id order by sale_date desc) last_price_usd
from mytable t
) t
where lag_price_usd is null or price > last_price_usd
在早期版本中,您可以使用相关子查询:
select t.*
from mytable t
where t.price_usd > (
select price_usd
from mytable t1
where t1.user_id = t.user_id
order by sale_date desc
limit 1
)
我正在尝试了解如何在 mySQL 中执行我通常在 python 中执行的操作。
我有一个销售额 table,列为 sale_date、user_id 和 price_USD。每行都是用户下的订单。 我想要一个新的 table,其中包含所有比用户最后一次下订单花费更多的订单(所以在这张图片中,只有黄色行)。
我知道如何获取每个用户的最后订单的 table,但我无法将其保存在数据库中。 我如何通过 user_id 将每一行的价格与不同的值进行比较,并在一个 'swoop' 中获得较大的价格?
谢谢
如果您是 运行 MysL 8.0,您可以使用 window 函数来完成此操作:
select t.*
from (
select
t.*,
first_value(price_usd)
over(partition by user_id order by sale_date desc) last_price_usd
from mytable t
) t
where lag_price_usd is null or price > last_price_usd
在早期版本中,您可以使用相关子查询:
select t.*
from mytable t
where t.price_usd > (
select price_usd
from mytable t1
where t1.user_id = t.user_id
order by sale_date desc
limit 1
)