计算生成两个以上发票的客户-mysql

时间:2019-03-13 18:28:31

标签: mysql sql

我要计算生成2张以上发票的客户数量

mysql> select * from invoices;
+-------+--------+---------------------+
| invId | cus_id | timeinfo            |
+-------+--------+---------------------+
|     1 |     36 | 2019-02-21 16:47:10 |
|     2 |     33 | 2019-02-21 16:49:22 |
|     3 |     34 | 2019-02-21 16:51:00 |
|     7 |     34 | 2019-02-21 19:02:46 |
|     5 |     36 | 2019-02-21 16:53:55 |
|     6 |     33 | 2019-02-21 19:02:02 |
|     8 |     33 | 2019-02-22 01:36:26 |
|     9 |     34 | 2019-02-22 16:01:20 |
|    10 |     33 | 2019-03-03 13:02:28 |
|    11 |     35 | 2019-03-05 19:11:53 |
|    12 |     32 | 2019-03-13 22:41:38 |
+-------+--------+---------------------+
11 rows in set (0.00 sec)

2 个答案:

答案 0 :(得分:1)

尝试如下

这将返回具有多个发票的客户ID

 select cus_id 
 from invoices
 group by cus_id 
 having count(*)>2

如果您只需要数字,则在下面使用它将返回仅客户数

select count(*) as numberofcustomer
 from (   select cus_id 
     from invoices
     group by cus_id 
    having count(*)>2 
     ) a

答案 1 :(得分:0)

您需要对cus_id值进行分组,并使用having子句,如下所示:

select cus_id, count(invId) as InvoiceCount
from invoices
group by cus_id
having count(invId) > 2

编辑:如果您需要客户总数,则应将上面的查询用作子查询:

select count(t.cus_id) as CustomerCount 
from (
   select cus_id, count(invId) as InvoiceCount
   from invoices
   group by cus_id
   having count(invId) > 2 
) t