MySql查询为客户选择总订单

时间:2016-03-22 06:43:20

标签: mysql sql

标题并不能很好地描述我对查询的需求。

@sgeddes帮助我提出了以下查询,但查询需要进行一些更改才能完成我的需求。我还略微修改了查询而没有选择已删除的客户,但由于编写此查询的方式不符合我的SQL知识,因此我无法进行太多更改。

SELECT  d.customer_id,d.fname,d.lname,d.isactive,
        o.lastdate, 
        Count(o2.order_id) AS 'total_orders'
 FROM   customers d
        LEFT JOIN (SELECT MAX(order_id) order_id, customer_id
              FROM   orders 
              GROUP BY customer_id) m on d.customer_id = m.customer_id
        LEFT JOIN orders o on m.order_id = o.order_id
        LEFT JOIN orders o2 on d.customer_id = o2.customer_id 
                           AND o2.balance > 0 AND o2.isActive > -1
 WHERE  d.user_id =945766  AND d.isActive > -1 
        AND o2.customer_id IS NULL
GROUP BY d.customer_id

我需要以下三个要求。

  1. 使用isActive>计算客户订单-1(-1 =删除)
  2. 客户不在订单表中(没有订单的客户)。
  3. isActive = 0的客户及其相应的订单数
  4. 所以我需要的是isActive = 0的客户以及获得total_orders列的实际#。

    为了更好地帮助您了解我的要求,我创建了一个SqlFiddle。

    Please see my SqlFiddle

1 个答案:

答案 0 :(得分:0)

如果您的要求是您在3分中提到的,那么您可以使用以下查询 -

如果您想要单独查询,请使用以下 -

SELECT d.customer_id, d.fname, COUNT(o.order_id) AS Total_Orders
FROM customer d 
LEFT JOIN orders o ON d.customer_id=o.customer_id 
WHERE d.isActive > -1
GROUP BY d.customer_id;

SELECT DISTINCT d.customer_id, d.fname 
FROM customer d 
LEFT JOIN orders o ON d.customer_id=o.customer_id 
WHERE o.customer_id IS NULL;

SELECT d.customer_id, d.fname, COUNT(o.order_id) AS Total_Orders
FROM customer d 
LEFT JOIN orders o ON d.customer_id=o.customer_id 
WHERE d.isActive = 0 
GROUP BY d.customer_id;

如果您想通过联合合并它们,请使用以下 -

SELECT 'isactive>-1' AS 'status', d.customer_id, d.fname, COUNT(o.order_id) AS Total_Orders
FROM customer d 
LEFT JOIN orders o ON d.customer_id=o.customer_id 
WHERE d.isActive > -1
GROUP BY d.customer_id 
UNION ALL
SELECT DISTINCT 'Customer without Order' AS 'status', d.customer_id, d.fname, COUNT(o.order_id) AS Total_Orders 
FROM customer d 
LEFT JOIN orders o ON d.customer_id=o.customer_id 
WHERE o.customer_id IS NULL 
UNION ALL
SELECT 'isactive=0' AS 'status', d.customer_id, d.fname, COUNT(o.order_id) AS Total_Orders
FROM customer d 
LEFT JOIN orders o ON d.customer_id=o.customer_id 
WHERE d.isActive = 0 
GROUP BY d.customer_id;

注意:您的主要查询是尝试获取最新订单,这可以用于任何其他目的,因此如果您提供的确切要求与其不同,那么有人可以帮助您。