我在Server中有一个关系数据库,用于存储产品、竞争对手公司和竞争对手的价格。我经常添加新的记录到竞争对手价格表,而不是更新现有的记录,以便我可以跟踪价格变化随时间推移。
我想建立一个查询,给出一个特定的产品,找到每一个竞争对手的最新价格。有可能每个竞争对手都没有价格记录。
数据示例
tblCompetitorPrices
+-----+----------+-------------+-----+----------+
|cp_id|product_id|competitor_id|price|date_added|
+-----+----------+-------------+-----+----------+
|1 |1 |3 |70.00|15-01-2014|
+-----+----------+-------------+-----+----------+
|2 |1 |4 |65.10|15-01-2014|
+-----+----------+-------------+-----+----------+
|3 |2 |3 |15.20|15-01-2014|
+-----+----------+-------------+-----+----------+
|4 |1 |3 |62.30|19-01-2014|
+-----+----------+-------------+-----+----------+我希望查询返回..。
+-----+----------+-------------+-----+----------+
|cp_id|product_id|competitor_id|price|date_added|
+-----+----------+-------------+-----+----------+
|4 |1 |3 |62.30|19-01-2014|
+-----+----------+-------------+-----+----------+
|2 |1 |4 |65.10|15-01-2014|
+-----+----------+-------------+-----+----------+我目前可以获得所有的产品价格,但我不能过滤结果,所以只显示了每个竞争对手的最新价格-我是真正的unsure...here是我到目前为止.
SELECT cp_id, product_id, competitor_id, price, date_added
FROM tblCompetitorPrices
WHERE product_id = '1'
ORDER BY date_added DESC谢谢你的帮助!
发布于 2014-01-19 13:28:29
作为另一种选择,您还可以使用ROW_NUMBER(),它是一个生成序列号的窗口函数。
SELECT cp_id,
product_id,
competitor_id,
price,
date_added
FROM (
SELECT cp_id,
product_id,
competitor_id,
price,
date_added,
ROW_NUMBER() OVER (PARTITION BY competitor_id
ORDER BY date_added DESC) rn
FROM tblCompetitorPrices
WHERE product_ID = 1
) a
WHERE a.rn = 1此查询可以很容易地修改,以返回每种产品中每个竞争对手的最新记录。
发布于 2014-01-19 13:18:00
尝尝这个,
SELECT cp_id, product_id, competitor_id, price, date_added
FROM tblCompetitorPrices
WHERE product_id = '1' AND date_added=( SELECT MAX(date_added)
FROM tblCompetitorPrices
WHERE product_id = '1')
ORDER BY date_added DESC发布于 2014-01-19 13:49:32
我花了一段时间,因为我不得不亲自测试这个查询,所以是的,它在这里。试一试,它可能会对你的从句组合有所帮助。)它更短。
SELECT cp_id, product_id, competitor_id, price, MAX(date_added) as last_date
FROM tblCompetitorPrices
WHERE product_id = '1'
GROUP BY competitor_idhttps://stackoverflow.com/questions/21217191
复制相似问题