使用两个聚合函数-同一查询上的min和max

时间:2019-03-05 08:59:43

标签: 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            C-11       10

我想获得每个产品类别的最大折扣,如果任何类别的多个产品具有相同的折扣,则该产品具有最小的折扣 应选择product_id。

所需的输出-

product_id  category    discount
64          C-10        10
294         C-11        17

我在下面两个查询中尝试过,但是没有用-

select category,min(product_id),max(discount)
from Product 
group by category

非常感谢您的帮助。谢谢!

3 个答案:

答案 0 :(得分:3)

在这里使用ROW_NUMBER很有帮助:

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

答案 1 :(得分:1)

使用row_number()

select * from
(
select *,row_number() over(partition by category order by discount desc, poroduct_id asc) rn
from tablename
)A where rn=1

或 使用相关子查询

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)

答案 2 :(得分:1)

使用外部应用

knex.destroy()

输出

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 

demo link