SQL选择具有最大值或不同值的行,然后对所有行求和

SQL选择具有最大值或不同值的行,然后对所有行求和,sql,sql-server,tsql,Sql,Sql Server,Tsql,我有以下返回给我的数据。我需要通过计税获得一个单独的或最大的佣金总额。“qtrlycommrep”列是我试图获取但无法获取的值。对于repnbr c590,我需要获得854.66佣金金额,这是每辆出租车的最高金额 我做错了什么 任何帮助都将不胜感激 这是我到目前为止试过的。使用行号 select distinct sub.Repnbr , (sub.QtrLYComm) as qtrlycommrep from ( select disti

我有以下返回给我的数据。我需要通过计税获得一个单独的或最大的佣金总额。“qtrlycommrep”列是我试图获取但无法获取的值。对于repnbr c590,我需要获得854.66佣金金额,这是每辆出租车的最高金额

我做错了什么

任何帮助都将不胜感激

这是我到目前为止试过的。使用
行号

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 top 1 with ties
        #qtrly.repnbr, #qtrly.qtrlycomm as qtrlycommrep

    from #qtrly 
        order by 
            row_number() over(partition by repnbr 
            order by qtrlycomm desc)
交叉应用

 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;
行号下单

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 top 1 with ties
        #qtrly.repnbr, #qtrly.qtrlycomm as qtrlycommrep

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

您希望每个税号有一个值。您需要包含该值。例如:

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;

我在这两个查询中都添加了taxid,这使我远离了需要到达的地方。糟糕的是,我不能在SSR中按嵌套组求和。@BIReportGuy。你是说这些都不是你想要的?他们应该处理您提供的示例数据。对不起,您的代码非常完美,但我在查询中尝试了很多。