令人困惑的SQL查询,分组依据?有?

时间:2014-01-19 13:12:19

标签: sql sql-server rdbms

我在SQL 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|
+-----+----------+-------------+-----+----------+

我目前可以访问该产品的所有价格,但我无法过滤结果,因此只显示每个竞争对手的最新价格 - 我真的不确定......这就是我所拥有的远....

SELECT cp_id, product_id, competitor_id, price, date_added 
FROM tblCompetitorPrices
WHERE product_id = '1' 
ORDER BY date_added DESC

感谢您的帮助!

3 个答案:

答案 0 :(得分:2)

试试这个,

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

答案 1 :(得分:1)

作为替代方案,您还可以使用ROW_NUMBER()这是一个生成序号的Window函数。

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

可以轻松修改此查询,以便为每个产品中的每个竞争对手返回最新记录。

答案 2 :(得分:0)

我花了一段时间才自己测试查询,所以是的,在这里。尝试一下,它甚至可以帮助你使用子句组合。 :)它更短。

SELECT cp_id, product_id, competitor_id, price, MAX(date_added) as last_date 
FROM tblCompetitorPrices
WHERE product_id = '1' 
GROUP BY competitor_id