我正试图找到一种方法,使用source和productId作为参考,在MySQL表中获得最大的价格差异(在一个时间范围内,例如24小时)。
以下是一个示例产品productId
22。
id price createdAt updatedAt sourceId productId
21 799.00 2017-07-26 19:46:46 2017-07-26 19:46:45 1 22
853 920.00 2017-07-26 06:46:46 2017-07-26 06:46:46 1 22
855 799.00 2017-07-22 16:17:11 2017-07-22 16:17:11 2 22
851 770.00 2017-07-21 16:17:11 2017-07-21 16:17:11 1 22
856 799.00 2017-07-20 16:17:11 2017-07-20 16:17:11 2 22
852 599.00 2017-07-19 16:17:11 2017-07-19 16:17:11 1 22
857 810.00 2017-07-18 16:17:11 2017-07-18 16:17:11 2 22
858 799.00 2017-07-17 16:17:11 2017-07-17 16:17:11 2 22
在上面的productId
22示例中,我按createdAt
进行排序,因此在这种情况下,我会使用ID 21
并从ID 853
中删除它,这将给-121
,意味着产品下降了121美元。
在完整数据中,它是prices
,sourceIds
和productIds
的糊涂。这里的目标是使结果看起来像这样:
id createdAt sourceId productId adjustment
21 2017-07-26 19:46:46 1 22 -121
22 2017-07-26 16:46:46 2 22 201
23 2017-07-26 15:46:46 6 24 -20
以上是我试图查看数据的方式,因此我知道每个来源的每个产品的价格差异。然后我可以控制数据,例如通过调整排序,看看哪个源+产品在时间范围内有最大的减少或增加。
我尝试过大量的子查询,我可能会在我从Google修改的一百个示例中加入。我可以将这部分内容拼凑在一起,例如只收到过去24小时内收到任何类型更改的产品。我尝试合并每个产品ID的最后两行,然后进行数学计算,并列出所有产品。尝试构建此查询已经过了2天,我最好不要对所有内容使用查询并在后端执行此操作吗?
我甚至去过像hackhands这样的支持网站,他们无法弄明白。我已经用尽了所有的想法。
答案 0 :(得分:2)
此查询解决了问题:
1)获取与每个产品的窗口的start_at时间相对应的记录,以获得基准价格。
2)获取时间范围内每个产品的最高价格记录。
3)获取时间范围内每个产品的最低价格记录。
4)将1和2和3组合在一起,形成每个产品的单个记录,并显示基线价格与时间范围内最高和最低之间的信息和差异。
如果你只需要两个中较大的一个,你可以添加和额外的选择包装这个查询和用户GREATER(a,b)保持一个差异或另一个。
select BOWPRICE.product_id, BOWPRICE.created_at, BOWPRICE.price,
MAXPRICE.max_price_upd_time, MAXPRICE.max_price, ABS((BOWPRICE.price - MAXPRICE.max_price)) max_price_diff,
MINPRICE.min_price_upd_time, MINPRICE.min_price, ABS((BOWPRICE.price - MINPRICE.min_price)) min_price_diff
from
(
select mainA.product_id, mainA.created_at, mainA.price from SOTEST mainA
where id in (
select id
from SOTEST N
where created_at = (
select min(N1.created_at)
from SOTEST N1
where N1.created_at >= '2017-07-26 00:00:00'
and N1.product_id = N.product_id
)
group by mainT.product_id
)
) BOWPRICE,
(
select mainB.product_id, mainB.updated_at max_price_upd_time, mainB.price max_price from SOTEST mainB
where id in(
select id from SOTEST M
where M.price = (
select max(M1.price)
from SOTEST M1
where M1.created_at >= '2017-07-26 00:00:00'
and M1.created_at < '2017-07-27 00:00:00'
and M1.product_id = M.product_id
group by product_id LIMIT 1
)
)
) MAXPRICE,
(
select mainC.product_id, mainC.updated_at min_price_upd_time, mainC.price min_price from SOTEST mainC
where id in(
select id from SOTEST Q
where Q.price = (
select min(Q1.price)
from SOTEST Q1
where Q1.created_at >= '2017-07-26 00:00:00'
and Q1.created_at < '2017-07-27 00:00:00'
and Q1.product_id = Q.product_id
group by product_id LIMIT 1
)
)
) MINPRICE
where BOWPRICE.product_id = MAXPRICE.product_id
and BOWPRICE.product_id = MINPRICE.product_id