数据库中2个表的计数功能

时间:2019-06-14 07:05:02

标签: sql count

我有2张这样的桌子

rental_tabel

id |    date       |   cust_id               |     driver_number
1     2019-01-02          1                         F 3350 NN
2     2019-04-02          2                         AX 111 Z
3     2019-05-02          3                         S 787  X
4     2019-05-02          4                         T 9090 M
5     2019-06-02          3                         P 8989 L

user_table

cust_id |   name       
1          John          
2          Doe
3          Michael
4          Leonard
5          Steve

如何计算在出租表中多次显示的客户名称?

我使用了计数功能,我可以对显示的ID进行多次计数,但仍然无法获得客户的名字

这是我的计数查询

SELECT COUNT(rental_table.cust_id) AS total FROM rental_table WHERE rental_table.cust_id>'1' 

结果是

| total   |
-----------
|   2     |

我可以在哪里添加以从该计数功能中获取客户名称?

1 个答案:

答案 0 :(得分:1)

您可以将GROUP BY cust_id与以下HAVING子句一起使用:

SELECT u.name
  FROM rental_table r
  JOIN user_table u
    ON u.cust_id = r.cust_id
 GROUP BY cust_id
HAVING count(cust_id) > 1