【问题标题】:Get last 2 updated unit_price from price changing table in last month从上个月的价格变化表中获取最近 2 个更新的 unit_price
【发布时间】:2018-08-14 04:45:18
【问题描述】:

我有一张表格,记录了每个 cost_price、unit_price 和 special_price 上商品的所有价格变化。即使其中一种定价从旧定价改变,该表也会记录数据。表结构示例如下。

 id | item_id | cost_price  | unit_price   | special_price | created_date
---------------------------------------------------------------------------
  1 |   101   |    100      |  NULL        |   NULL        | 2018-07-15 10:02:20
  2 |   102   |   NULL      |  250         |   NULL        | 2018-07-16 12:23:00
  3 |   101   |   NULL      |  150         |   NULL        | 2018-07-16 10:02:20
  4 |   101   |   NULL      |  200         |   NULL        | 2018-07-18 12:23:00
  5 |   101   |   NULL      |  201         |   NULL        | 2018-07-22 10:02:20
  6 |   102   |   NULL      |  283         |   NULL        | 2018-07-28 12:23:00

我想从上个月的表格(日期为 13-07-2018)中获得以下输出

item_id   |   unit_price   | changed_date
-----------------------------------------
   101    |    201         | 2018-07-22 10:02:20
   101    |    200         | 2018-07-18 12:23:00
   102    |    283         | 2018-07-28 12:23:00

我需要上面的输出,它只显示 unit_price 中发生的最后两个变化。

【问题讨论】:

  • Mysql版本?
  • 这未能解决问题的哪一部分:select * from my_table order by changed_date desc limit 3?
  • @skelwa mysql 5.6版
  • @Strawberry Query 只需要获取上个月内最近 2 次不同的 unit_price 变化。
  • 你的主键是什么?

标签: mysql sql query-optimization


【解决方案1】:

这可能看起来很复杂:

SELECT t1.item_id,t1.unit_price,t1.created_date AS changed_date
FROM table_name t1 INNER JOIN 
   (
    SELECT a.item_id, a.unit_price, MAX(a.created_date) AS changed_date
    FROM table_name a INNER JOIN 
    (SELECT item_id, unit_price, MAX(created_date) AS changed_date
    FROM table_name GROUP BY item_id, unit_price) b
    ON a.item_id =  b.item_id and a.created_date < b.changed_date
    GROUP BY a.item_id, a.unit_price
   ) t2
   ON t1.item_id = t2.item_id AND t1.created_date >= t2.changed_date

【讨论】:

    【解决方案2】:

    对于每个项目,您最多需要最后两个更改。在 MySQL(V8 之前)中,您可以使用变量:

    select t.*
    from (select t.*,
                 (@rn := if(@i = item_id, @rn + 1,
                            if(@i := item_id, 1, 1)
                           )
                 ) as rn
          from (select t.*
                from t
                order by t.item_id, t.changed_date desc
               ) t cross join
               (select @i := -1, @rn := 0) params
         ) t
    where rn <= 2;
    

    【讨论】:

    • 我遇到的问题是,我只想获取每件商品的最后两个 unit_price 更改。在表数据中,当cost_price或special_price发生变化时,unit_price的值为NULL。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-08
    • 2014-10-23
    • 1970-01-01
    • 1970-01-01
    • 2021-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多