[英]SQL - get minimum price based with date range
I have a database containing prices from various suppliers for the same product. 我有一个数据库,其中包含来自同一产品的各个供应商的价格。 Each supplier/product combination has a start & end date with a product ID and price
每个供应商/产品组合都有一个开始和结束日期以及产品ID和价格
id | pid | aid | start_date | end_date | price
1 | 1 | 1 | 2017-01-01 | 2017-01-10 | 10.00
1 | 1 | 2 | 2017-01-01 | 2017-01-05 | 12.00
1 | 1 | 2 | 2017-01-06 | 2017-01-09 | 9.00
I use a calendar table to make sure I have all the dates in a certain range. 我使用日历表来确保所有日期都在一定范围内。 The struggle I have is to select the min price given a certain date range.
我要做的就是在给定日期范围内选择最低价格。 The above data should output as below.
以上数据应输出如下。
date | aid | price
2017-01-01 | 1 | 10.00
2017-01-02 | 1 | 10.00
2017-01-03 | 1 | 10.00
2017-01-04 | 1 | 10.00
2017-01-05 | 1 | 10.00
2017-01-06 | 2 | 9.00
2017-01-07 | 2 | 9.00
2017-01-08 | 2 | 9.00
2017-01-09 | 2 | 9.00
2017-01-10 | 1 | 10.00
Just having one supplier and getting the price is not an issue, but as soon as I start grouping the data I only get one result or an incorrect result. 仅拥有一个供应商并获得价格不是问题,但是,一旦我开始对数据进行分组,我只会得到一个结果或不正确的结果。 I'm using this query, which provides the wrong outcome.
我正在使用此查询,它提供了错误的结果。
SELECT
c.date, min(p.price) as min_price
FROM
bricks_calender c
LEFT JOIN
bricks_prijzen p ON c.date BETWEEN p.start_date AND p.end_date
WHERE
p.pid = 1
GROUP BY
aid
ORDER BY
c.date
Any suggestion where I need to update this query, to get the expected outcome? 有什么建议我需要更新此查询以获得预期结果吗? Or should I change my data model (which is of course not preferred)
还是应该更改我的数据模型(当然不是首选)
If bricks_calender contains one row per date, the follow should work: 如果bricks_calender每个日期包含一行,则应执行以下操作:
SELECT
c.`date`,
(select s.`aid` from `bricks_prijzen` s where s.`price` = min(p.`price`) and c.`date` BETWEEN s.`start_date` AND s.`end_date` ORDER BY s.`price` ASC LIMIT 0,1) AS `aid`,
min(p.`price`) as `min_price`
FROM `bricks_calender` c
LEFT JOIN `bricks_prijzen` p
ON c.`date` BETWEEN p.`start_date` AND p.`end_date`
WHERE
p.`pid` = 1
GROUP BY
c.`date`
ORDER BY
c.`date`;
I think it's simply because you group your data by aid
with GROUP BY aid
, so you can't have more row than the number of different aid
that exist. 我认为这只是因为你按你的数据
aid
与GROUP BY aid
,所以你不能比不同数量多行aid
存在。
By unsetting this GROUP BY
, does it solve the problem? 通过取消设置
GROUP BY
,是否可以解决问题?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.