首页 > 解决方案 > SQL选择具有最大值或不同值的行并将所有值相加

问题描述

我有以下数据返回给我。我需要通过为单个 repnbr 计费来获得所有佣金的不同或最大总和。'qtrlycommrep' 列是我试图达到但无法达到的值。对于 repnbr c590,我需要获得 854.66 的佣金金额,这是每个出租车的最大值。

我究竟做错了什么?

任何帮助将非常感激!

在此处输入图像描述

这是我到目前为止所尝试的。使用Row_number

select distinct 
        sub.Repnbr
    ,   (sub.QtrLYComm) as qtrlycommrep
   from ( 
        select distinct repnbr, QtrLYComm
        , rn = row_number() over(partition by repnbr order by QtrLYComm desc)

    from #qtrly
    ) sub
    where sub.rn = 1

交叉申请

 select distinct
        #qtrly.repnbr
    ,   x.QtrLYComm as qtrlycommrep

    from #qtrly
        cross apply (
            select top 1
                *
            from #qtrly as i
            where i.repnbr = Repnbr
            order by i.qtrlycomm desc
            ) as x;

内部联接

select
    #qtrly.repnbr, #qtrly.qtrlycomm as qtrlycommrep

 from #qtrly 
    inner join (
    select maxvalue = max(qtrlycomm), repnbr
    from #qtrly
    group by repnbr
    ) as m
    on #qtrly.repnbr = m.repnbr 
    and #qtrly.qtrlycomm = m.maxvalue;

订购row_number

  select top 1 with ties
        #qtrly.repnbr, #qtrly.qtrlycomm as qtrlycommrep

    from #qtrly 
        order by 
            row_number() over(partition by repnbr 
            order by qtrlycomm desc)

标签: sqlsql-servertsql

解决方案


您希望每个税号都有一个值。你需要包括它。例如:

select q.Repnbr, sum(q.QtrLYComm) as qtrlycommrep
from (select q.*,
             row_number() over(partition by repnbr, taxid order by QtrLYComm desc) as seqnum
      from #qtrly q
     ) q
where seqnum = 1
group by q.Repnbr;

但是,我倾向于使用两个级别的聚合:

select q.Repnbr, sum(q.QtrLYComm) as qtrlycommrep
from (select distinct repnbr, taxid, QtrLYComm
      from #qtrly q
     ) q
group by q.Repnbr;

推荐阅读