【问题标题】:Filtering values according to a different value for each user根据每个用户的不同值过滤值
【发布时间】:2020-05-27 17:40:54
【问题描述】:

我正在尝试了解如何在 mySQL 中执行我通常在 python 中执行的操作。

我有一个销售表,其中包含 sale_date、user_id 和 price_USD 作为列。每一行都是用户下的一个订单。 我想获得一个新表,其中包含所有成本高于用户上次订单的订单(所以在这张图片中,只有黄色行)。

我知道如何获取每个用户的最后订单表,但我无法将其保存在数据库中。 如何将每一行的价格与 user_id 的不同值进行比较,并一次性获得较大的价格?

谢谢

【问题讨论】:

    标签: mysql sql date greatest-n-per-group window-functions


    【解决方案1】:

    如果您运行的是 MysL 8.0,您可以使用窗口函数来执行此操作:

    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
    )
    

    【讨论】:

      猜你喜欢
      • 2020-09-01
      • 2022-01-17
      • 2021-10-17
      • 1970-01-01
      • 2021-10-12
      • 1970-01-01
      • 2015-03-26
      • 2021-10-17
      • 1970-01-01
      相关资源
      最近更新 更多