计算他们在MySQL中只有1个订单的客户数量

时间:2014-03-07 11:43:46

标签: mysql

我正在使用MySQL数据库服务器。我的疑问是:

  

计算他们只有1个订单的客户数量以及他们拥有超过1个订单的客户数量。

这是我的SQL查询:

SELECT 
    COUNT((SELECT 
            customer_code
        FROM
            customer AS c
                LEFT JOIN
            order_info AS oi ON (c.customer_code = oi.customer_code)
        GROUP BY customer_code
        HAVING COUNT(id_order) = 1)) AS New_customers

我怎样才能得到这个结果。

5 个答案:

答案 0 :(得分:2)

您在计算之前按customer_code进行分组,我认为这会将行分组在一起,从而有效地从结果集中删除所有订单。 HAVING始终将结果集用作“数据Feed”。

SELECT 
    COUNT(DISTINCT customer_code)
FROM
    customer AS c
LEFT JOIN order_info AS oi ON (c.customer_code = oi.customer_code)

HAVING COUNT(id_order) = 1

或者更简单(但可能没有更高效)

SELECT 
    COUNT(customer_code)
FROM
    customer AS c
WHERE (
    SELECT 
        COUNT(*) 
    FROM `order_info` 
    WHERE 
        `customer_code` = `c`.`customer_code`
) = 1

要获得包含多个订单的客户数量,只需将=更改为适当的>

答案 1 :(得分:0)

SELECT 
count(customer_code)
FROM
customer AS c
LEFT JOIN
order_info AS oi ON (c.customer_code = oi.customer_code)
GROUP BY customer_code
HAVING COUNT(id_order) = 1

答案 2 :(得分:0)

For customers having 1 order

SELECT count(customer_code) FROM customer AS c
INNER JOIN order_info AS oi ON (c.customer_code = oi.customer_code)
GROUP BY customer_code HAVING COUNT(id_order) = 1))


 For customers having MORE THAn 1 order

SELECT count(customer_code) FROM customer AS c
INNER JOIN order_info AS oi ON (c.customer_code = oi.customer_code)
GROUP BY customer_code HAVING COUNT(id_order) > 1))

答案 3 :(得分:0)

试试这个

SELECT 
count(*)
FROM
customer AS c
LEFT JOIN
order_info AS oi ON c.customer_code = oi.customer_code
HAVING COUNT(id_order) = 1

答案 4 :(得分:0)

试试这个:

  SELECT * FROM ( select c.customer_code, count(*) total FROM customer c
  LEFT JOIN
  order_info AS oi ON (c.customer_code = oi.customer_code) 
  GROUP BY customer_code) test
  CASE total
  WHEN 1 THEN SELECT total one_order FROM test;
  ELSE 
  SELECT total more_order FROM test