如何在使用“分组依据”时从每个组中查找最大值并显示其信息

时间:2016-12-26 13:09:37

标签: sql sql-server

例如,我创建了一个关于人们参与2个广告系列的表格

+-------------------------------------+
| ID    Name   Campaign  Amount (USD) |
+-------------------------------------+
| 1      A         1             10   |
| 2      B         1             5    |
| 3      C         2             7    |
| 4      D         2             9    |
+-------------------------------------+

任务:对于每个广告系列,找到贡献最多的人(姓名,ID)

预期结果是

+-----------------------------------------+
|     Campaign          Name           ID |
+-----------------------------------------+
|     1                 A              1  |
|     2                 D              4  |
+-----------------------------------------+

我使用“按广告系列分组”,但当我需要“名称”和“ID”时,结果有2列“Campagin”和“max value”

感谢您的帮助。 编辑:我修正了一些值,真的很抱歉

5 个答案:

答案 0 :(得分:3)

您可以使用分析函数:

select name, id, amount
from (select t.*, max(amount) over (partition by campaign) as max_amount
      from t
     ) t
where amount = max_amount;

答案 1 :(得分:1)

您也可以按campaign给出排名/行号分区,然后按amount的降序排序。

<强>查询

;with cte as(
    select [num] = dense_rank() over(
        partition by [Campaign]
        order by [Amount] desc
    ), *
    from [your_table_name]
)
select [Campaign], [Name], [ID]
from cte
where [num] = 1;

答案 2 :(得分:0)

尝试下一个查询: -

 SELECT Campaign  ,  Name  ,    ID 
 FROM (
       SELECT Campaign  ,  Name  ,    ID , MAX (Amount)
         FROM MyTable
       GROUP BY Campaign , Name , ID
 ) temp;

答案 3 :(得分:0)

简单使用Where条款max金额group by广告系列: -

如下通用代码: -

select a,  b , c
from tablename
where d in
(
    select  max(d) 
    from tablename
    group by a
) 

演示: -

Create table #MyTable (ID int , Name char(1), Campaign int , Amount int)
go

insert into #MyTable values (1,'A',1,10)
insert into #MyTable values (2,'B',1,5)
insert into #MyTable values (3,'C',2,7)
insert into #MyTable values (4,'D',2,9)
go

select Campaign,  Name , ID
from #MyTable
where Amount in
(
    select  max(Amount) 
    from #MyTable
    group by Campaign
) 

drop table #MyTable

<强>结果: -

enter image description here

答案 4 :(得分:0)

请找到相同的

的以下代码
SELECT * 
FROM #MyTable T
OUTER APPLY (
    SELECT COUNT(1) record 
    FROM #MyTable T1
    where t.Campaign = t1.Campaign
    and t.amount < t1.amount
)E
where E.record = 0