最近x天以相同价格获取产品

时间:2018-09-24 23:33:37

标签: mysql amazon-redshift

我想获取那些最近5天内连续在MYSQL中报告相同价格的产品。我在下面随附了示例数据供您参考。

PID Price   Date
P1  10  25-09-2018
P1  10  24-09-2018
P1  10  23-09-2018
P1  10  22-09-2018
P1  10  21-09-2018
P2  25  25-09-2018
P2  25  24-09-2018
P2  30  23-09-2018
P2  25  22-09-2018
P2  25  21-09-2018
P3  50  25-09-2018
P3  48  22-09-2018
P4  15  23-09-2018
P4  15  21-09-2018

所需的输出应该是

PID Price
P1  10
P4  15

谢谢。

2 个答案:

答案 0 :(得分:0)

使用示例数据,您可以尝试类似于下一个伪MySQL查询的查询:

SELECT
    Column_PID,
    Column_Price,
FROM
    the_table
WHERE
    Column_Date >= (NOW() - INTERVAL 4 DAY)
GROUP BY
    Column_PID, Column_Price
HAVING count(Column_Date) >= 5

答案 1 :(得分:0)

  • 利用Correlated subquery为每个PIDdate(上一个日期的价格)确定一个“上一个价格”。

  • 仅考虑最近 5 天的数据(您可以将其设置为变量)。

  • 使用Derived tables并在PID上分组,过滤(使用Having子句),其中更改的MINMAX为0

使用以下查询:

SELECT inner_nest.PID, 
       MAX(inner_nest.Price) AS Price 
FROM 
(
  SELECT t1.PID, t1.Price, 
         (SELECT t2.Price 
          FROM your_table AS t2 
          WHERE t2.PID = t1.PID 
            AND t2.date < t1.date 
          ORDER BY t2.date DESC LIMIT 1) AS previous_price  
  FROM your_table AS t1 
  WHERE DATEDIFF( NOW(), t1.date ) < 5
) AS inner_nest 
GROUP BY inner_nest.PID 
HAVING MIN(inner_nest.Price - inner_nest.previous_price) = 0 
   AND MAX(inner_nest.Price - inner_nest.previous_price) = 0