我正在尝试为其中一张发票选择所有佣金数据,该发票将向最高销售人员支付佣金。 (可以为每张发票支付多个佣金。)我只有CommissionReport表,其中包含每张发票的每个销售人员的佣金。
invoice_number salesperson_id commission_amt
---------------- ---------------- ----------------
1001 Bob 30.00
1002 Alison 64.50
1002 Charlie 110.25
这段代码工作正常,但我的潜意识是尖叫,我不需要嵌套三个深度的子选择。有人可以帮我理顺吗?
select
invoice_number,
salespeson_id,
commission_amt
from
CommissionReport CR
join
( select top 1 invoice_number
from CommissionReport CR2
group by CR2.invoice_number
having count(*) =
( select max(CR3.cnt)
from
( select invoice_number,
cnt = count(*)
from CommissionReport CR4
group by invoice_number
) CR3
)
) CR2 on CR2.invoice_number = CR.invoice_number
非常感谢。
斯科特
答案 0 :(得分:1)
我不明白这些要求,这是我在Mssql中的第一个查询...但检查一下是否有效:
select cr.invoice_number, cr.salesperson_id, cr.commission_amt
from CommissionReport CR
where cr.invoice_number in (
select top 1 invoice_number
from CommissionReport CR2
group by CR2.invoice_number
order by count(*) desc
)