子查询中的SQL COUNT

时间:2018-11-15 11:18:11

标签: sql count

我有一张餐桌订单(id,customer,service_area)

我需要找到在service_area中下了2个以上订单的客户数量,并显示已完成订单的客户数量。我发现,这显示的客户数量多于x个订单。

SELECT COUNT(*)
FROM (SELECT DISTINCT(COUNT(id)) FROM orders GROUP BY customer HAVING 
COUNT(id)>=x) AS Custom_count;

编辑:

sample data
id|   customer   | service_area
--------------------------------
 1|     c1       |   ser1
 2|     c1       |   ser1
 3|     c1       |   ser1
 4|     c1       |   ser1
 5|     c2       |   ser2
 6|     c2       |   ser2
 7|     c3       |   ser1
 8|     c3       |   ser1

应该看起来像这样

Service area | No. of customers that placed x orders in the service area
------------------------------------------------------------------------
             |
             |
             |

4 个答案:

答案 0 :(得分:0)

您可能想要:

SELECT o.service_area, COUNT(o.customer)
FROM orders o
GROUP BY o.service_area;

如果您希望唯一的客户数在DISTINCT内使用COUNT()

答案 1 :(得分:0)

我想你需要这个:

select service_area, count(distinct customer)  customer_cnt
  from orders
 group by service_area
having count(id) > :your_variable_order_count

答案 2 :(得分:0)

您似乎想要:

SELECT COUNT(*)
FROM (SELECT customer, COUNT(DISTINCT service_area) as num_service_area
      FROM orders
      GROUP BY customer
     ) c
WHERE num_service_area > 2;

也就是说,子查询通过customer进行汇总并计算服务区域的数量。然后,外部查询会计算满足您指定条件的客户。

答案 3 :(得分:0)

使用TSQL Server语法:

declare @variable int = 1;
SELECT service_area,NoOfCust
FROM 
    (
     SELECT service_area, COUNT(id) as NoOfCust FROM orders group by service_area HAVING 
     COUNT(service_area)>= @variable
    ) AS Custom_count;