Postgresql如何计算最大计数()

时间:2017-03-20 19:17:12

标签: postgresql max

我试图找出一种计算最大计数(r.customer_id)的方法。运行脚本时,有4个值具有相同的最高值,因此我需要生成的是具有这4个值的表

SELECT     c1.customer_id, c1.first_name, c1.last_name, count(r.customer_id)
FROM       customer c1 
INNER JOIN rental r 
ON         (c1.customer_id = r.customer_id)  
WHERE      r.staff_id = 2 
GROUP      BY c1.customer_id, c1.first_name, c1.last_name
ORDER BY   4 desc

1 个答案:

答案 0 :(得分:0)

    SELECT customer_id, first_name, last_name, count 
      FROM (
      SELECT c1.customer_id as customer_id, c1.first_name as first_name, c1.last_name as last_name, count(r.customer_id) as count
      FROM customer c1 
      INNER JOIN rental r ON ( c1.customer_id = r.customer_id  )  
      WHERE r.staff_id = 2 
      GROUP BY c1.customer_id, c1.first_name, c1.last_name
    ) x 
    GROUP BY customer_id, first_name, last_name
    HAVING count = max(count)
    order by 4 desc