如何查询MySQL以获得COUNT的SUM?

时间:2016-02-24 19:19:29

标签: mysql database rdbms

我遇到了一个问题:"谁是数据库中的顶级租户?"到目前为止,我已经几乎完成了。至少,据我所知。

到目前为止,我在查询中的内容是:

SELECT customer.first_name, customer.last_name, 
  COUNT(rental.rental_id) AS `Total Rentals` 
FROM customer
INNER JOIN rental
ON rental.customer_id = customer.customer_id
GROUP BY customer.last_name, rental.rental_id
ASC LIMIT 25;

LIMIT 25仅用于测试目的,只是为了让表中有两位客户可以管理。

此查询产生:

+------------+-----------+---------------+
| first_name | last_name | Total Rentals |
+------------+-----------+---------------+
| RAFAEL     | ABNEY     |             1 |
| RAFAEL     | ABNEY     |             1 |
| RAFAEL     | ABNEY     |             1 |
| RAFAEL     | ABNEY     |             1 |
| RAFAEL     | ABNEY     |             1 |
| RAFAEL     | ABNEY     |             1 |
| RAFAEL     | ABNEY     |             1 |
| RAFAEL     | ABNEY     |             1 |
| RAFAEL     | ABNEY     |             1 |
| RAFAEL     | ABNEY     |             1 |
| RAFAEL     | ABNEY     |             1 |
| RAFAEL     | ABNEY     |             1 |
| RAFAEL     | ABNEY     |             1 |
| RAFAEL     | ABNEY     |             1 |
| RAFAEL     | ABNEY     |             1 |
| RAFAEL     | ABNEY     |             1 |
| RAFAEL     | ABNEY     |             1 |
| RAFAEL     | ABNEY     |             1 |
| RAFAEL     | ABNEY     |             1 |
| RAFAEL     | ABNEY     |             1 |
| RAFAEL     | ABNEY     |             1 |
| NATHANIEL  | ADAM      |             1 |
| NATHANIEL  | ADAM      |             1 |
| NATHANIEL  | ADAM      |             1 |
| NATHANIEL  | ADAM      |             1 |
+------------+-----------+---------------+

现在,我想要的是:

+------------+-----------+---------------+
| first_name | last_name | Total Rentals |
+------------+-----------+---------------+
| RAFAEL     | ABNEY     |            22 |
| NATHANIEL  | ADAM      |            23 |
...

等等。

我尝试做SUM(COUNT(rental.rental_id)),但显然,由于执行顺序,这不起作用。

我的问题是我需要做的而不是那个。我觉得自己走在了正确的轨道上,而且我还缺少一件小事。或者,我可能会非常失望。

无论哪种方式,谢谢你的帮助。

2 个答案:

答案 0 :(得分:0)

SELECT customer.customer_id,
       customer.first_name, 
       customer.last_name, 
       COUNT(rental.rental_id) AS `Total Rentals` 
FROM customer
INNER JOIN rental
        ON rental.customer_id = customer.customer_id
GROUP BY customer.customer_id,
         customer.first_name, 
         customer.last_name  -- USE THIS GROUP BY

答案 1 :(得分:0)

首先按customer_id查询租借表组:

SELECT customer_id, COUNT(rental_id) AS total
FROM rental
GROUP BY customer_id

然后将结果加入到客户表中:

SELECT customer.first_name, customer.last_name, r.total AS `Total Rentals` 
FROM (
  SELECT customer_id, COUNT(rental_id) AS total
  FROM rental
  GROUP BY customer_id
) r
INNER JOIN customer ON r.customer_id = customer.customer_id