why does this give me the wrong customerNumber?

后端 未结 3 1232
南方客
南方客 2021-01-26 05:29

I tried to get the customer that pay the maximum amount. It gave me the maximum amount but the wrong customer. what should i do?

SELECT temp.customerNumber, MAX         


        
相关标签:
3条回答
  • 2021-01-26 05:47

    Using a join, possibly as follows:-

    SELECT *
    FROM payments
    INNER JOIN
    (
        SELECT MAX(amount) AS MaxAmount
        FROM payments
    ) Sub1
    ON payments.amount = Sub1.MaxAmount
    

    Down side of this is that if 2 people both have the same high payment then both will be returned.

    0 讨论(0)
  • 2021-01-26 06:01

    I don't think you need the Subquery here:

    SELECT p.customerNumber, MAX(p.amount) AS max
    FROM payments p
    GROUP BY p.customerNumber
    ORDER BY max DESC
    LIMIT 1
    
    0 讨论(0)
  • 2021-01-26 06:04

    Consider that your subselect will return something like

    customerNumber amount
    1              100
    2              200
    

    Then the outer query will pull up those customer numbers and the MAX of ALL the rows, which breaks the link between customer numbers and their respective amounts. You're forcing the LARGES amount from ALL of the groups to be applied to all of the groups:

    cN   amount
    1    200
    2    200
    
    0 讨论(0)
提交回复
热议问题