sql - 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)
解决方案
您希望每个税号都有一个值。你需要包括它。例如:
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;
推荐阅读
- python - 编辑属性而不转义字符
- r - 是否可以根据注释而不是聚类结果为 kmeans 结果着色?
- c - 与挂在 C 中读取的子进程的通信
- ios - 从两个api中获取值到两个不同的Observable中并执行一些操作
- rust - 我可以将 RMPV `Value` 发送回 rmp_serde 进行反序列化吗?
- python - 如何创建一个 python 脚本,以便在目录中的 csv 文件在过去 24 小时内未更新时发送电子邮件?
- node.js - 试图将快速 API 代码移动到控制器文件
- elasticsearch - Kibana 可视化数据表 - 单独列中聚合函数之间的区别
- r - 使用 for 循环绘制不同的颜色
- flutter - AnimatedContainer 内的文本溢出