用于最低价格的SQL筛选器

用于最低价格的SQL筛选器,sql,sql-server,Sql,Sql Server,我有一个巨大的定价数据表,包括以下几列 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, 1

我有一个巨大的定价数据表,包括以下几列

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
谢谢你的帮助。谢谢。

您可以使用排号:

或者根据代码编写者的评论,您可以使用MIN和GROUP BY:

使用“不存在”返回同一来源不存在较低价格的行:

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)
等等


如果出现平局,两行都将返回

到目前为止,您编写的代码是什么?请按源、产品、术语、里程分组,然后选择源、产品、术语、里程、最小价格您的预期输出与示例数据不匹配。
SELECT
    source, product, term, miles, MIN(price) AS price
FROM [table_name]
GROUP BY source, product, term, miles
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)
SELECT
    source, product, term, miles, MIN(price) AS price
FROM [table_name]
GROUP BY source, product, term, miles