Scott
Scott

Reputation: 95

Simplify nested subselects containing aggregates

I'm trying to select all commission data for one of the invoice that will pay commissions to the highest number of sales people. (Multiple commissions can be paid for each invoice.) I have only the CommissionReport table, which contains commissions for each sales person for each invoice.

invoice_number     salesperson_id    commission_amt
----------------   ----------------  ----------------
            1001   Bob                          30.00
            1002   Alison                       64.50
            1002   Charlie                     110.25

This code works fine, but my subconcious is screaming that I don't need to nest subselects three deep. Can someone please straighten me out?

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

Thanks very much in advance.

Scott

Upvotes: 1

Views: 131

Answers (1)

Mosty Mostacho
Mosty Mostacho

Reputation: 43464

I didn't understand the requirements and this is my first query in Mssql... but check if this works:

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
)

Upvotes: 1

Related Questions