簡體   English   中英

SQL select 具有最大值或不同值的行並將所有值相加

[英]SQL select row with max value or distinct value and sum all

我有以下數據返回給我。 我需要通過為單個 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)

您希望每個稅號都有一個值。 你需要包括它。 例如:

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM