Sql 在同一查询中使用两个聚合函数-min和max
这是我的产品表数据-Sql 在同一查询中使用两个聚合函数-min和max,sql,sql-server,aggregate-functions,Sql,Sql Server,Aggregate Functions,这是我的产品表数据- product_id category discount 454 C-10 10 357 C-10 9 64 C-10 10 294 C-11 17 449 C-11 17 471 C-11 17 89 C-11 12 56
product_id category discount
454 C-10 10
357 C-10 9
64 C-10 10
294 C-11 17
449 C-11 17
471 C-11 17
89 C-11 12
56 C-11 10
我想获得每个产品类别的最大折扣,如果任何类别有多个具有相同折扣的产品,则该产品具有最小折扣
应选择产品标识
期望输出-
product_id category discount
64 C-10 10
294 C-11 17
我尝试了以下两个问题,但都不起作用-
select category,min(product_id),max(discount)
from Product
group by category
非常感谢你的帮助。谢谢 使用
行号
在这里很有帮助:
WITH cte AS (
SELECT product_id, category, discount,
ROW_NUMBER() OVER (PARTITION BY category
ORDER BY discount DESC, product_id) rn
FROM Product
)
SELECT product_id, category, discount
FROM cte
WHERE rn = 1;
或者,我们甚至可以在不使用子查询/CTE的情况下执行此操作:
SELECT TOP 1 WITH TIES product_id, category, discount
FROM Product
ORDER BY
ROW_NUMBER() OVER (PARTITION BY category
ORDER BY discount DESC, product_id);
使用行编号()
或
使用相关子查询
select * from tablename a where discount in
(select max(discount) from tablename b where a.category=b.category
having min(b.product_id)=a.product_id)
使用外部应用程序
with cte as
(
select 454 as product_id, 'C-10' as category, 10 as discount union all
select 357,'C-10',9 union all
select 64,'C-10',10 union all
select 294,'C-11',17 union all
select 449,'C-11',17 union all
select 471,'C-11',17 union all
select 89,'C-11', 12 union all
select 56,'C-11', 10
) select distinct p1.category,a.product_id,a.discount
from cte p1
outer apply ( select top 1 p2.*
from cte p2 where p1.category=p2.category
order by discount desc, product_id asc
) a
输出
category product_id discount
C-10 64 10
C-11 294 17
category product_id discount
C-10 64 10
C-11 294 17