我有一张庞大的定价数据表,其中包含以下列
source, product, term, miles, price
数据看起来像这样
LL, PH, 3, 10000, 100.00
BA, PH, 3, 10000, 200.00
LL, CH, 3, 10000, 300.00
BA, CH, 3, 10000, 400.00
我需要创建一个查询来过滤行,以便仅显示每个唯一来源/产品/期限/里程组合的最低价格的行。因此,在上面的示例中,我希望最终得到:
LL, PH, 3, 10000, 100.00
BA, PH, 3, 10000, 200.00
任何帮助表示赞赏。感谢。
答案 0 :(得分:3)
您可以使用ROW_NUMBER()
:
SELECT
source, product, term, miles, price
FROM(
SELECT *,
RN = ROW_NUMER() OVER(PARTITION BY source, product, term, miles ORDER BY price)
FROM [your_table]
)t
WHERE RN = 1
或根据代码的编码评论,您可以使用MIN()
和GROUP BY
:
SELECT
source, product, term, miles, price = MIN(price)
FROM [your_table]
GROUP BY source, product, term, miles
答案 1 :(得分:0)
使用NOT EXISTS
返回同一来源不存在较低价格的行:
select source, product, term, miles, price
from tablename t1
where not exists (select 1 from tablename t2
where t1.source = t2.source
and t2.price < t1.price)
如果您希望源/产品组合具有最低价格,请将产品添加到子选择条件中:
select source, product, term, miles, price
from tablename t1
where not exists (select 1 from tablename t2
where t1.source = t2.source
and t1.product = t2.product
and t2.price < t1.price)
等
如果有平局,则会返回两行!
答案 2 :(得分:-1)
SELECT
source, product, term, miles, MIN(price) AS price
FROM [table_name]
GROUP BY source, product, term, miles