MySQL子查询在同一个表中

时间:2011-03-09 08:28:34

标签: mysql select subquery

我有一张桌子可以从客户收取付款。我希望从前3位客户那里为每位客户付款。

以下查询会获得每个小时的每个小时的总付款。

SELECT
    hour(received) as hr,
    login,
    count(*) as total 
FROM
    payment
WHERE
    received >= date("2011-02-24")
AND
    received <date("2011-02-25")  
AND
    PAYMENT_BATCH_FILE_ID is null
GROUP BY
    hr,
    client_id 
ORDER BY
    hr,
    total DESC

以下查询在一小时内为每个客户提供前三名客户

SELECT
    hour(received) as hr,
    login,
    count(*) as total 
FROM 
    payment
WHERE 
    received >=date("2011-02-24") 
AND 
    received < date("2011-02-25")  
AND 
    PAYMENT_BATCH_FILE_ID is null 
AND
    hour(received)="3"
GROUP BY
    hr,
    client_id 
ORDER BY
    hr,
    total DESC
LIMIT 3

如何将这两个查询结合起来,以获得每小时付款的前三名客户?

感谢。

1 个答案:

答案 0 :(得分:0)

这是一个复杂的问题。请参阅此链接http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/

祝你好运!