查找按天分组的超过1个订单的客户

时间:2013-09-06 19:49:29

标签: mysql sql

我想知道有多少客户放置了超过1个订单,按天分组。 但我想排除已被取消的订单。

  • 我有客户的客户表

  • 我有一个带订单的customer_order表(订单被取消时) 它保留在customer_order表中)

  • 我有一个order_item表(原始订单在哪里,也是 取消订单,取消订单获得新的信用订单,以及 原始订单ID出现在信用证的id_credit_order行中 顺序)

我想要这样的事情:

date  |  no of customers with 1 order  |  no of customers with 2 orders  |  no of customers with 3 order  |  etc.

但如果原始订单被取消,我不想要数!

我现在有了这个查询,但它绝对不够,有人知道如何获得我的结果吗?谢谢!

SELECT DATE(co.date_order), COUNT(co.id_customer)
FROM customer_order co
GROUP BY DATE(co.date_order)
ORDER BY DATE(co.date_order) DESC;

3 个答案:

答案 0 :(得分:1)

这个问题有点误导,因为您首先要求的客户数量超过一个,然后您要求每个1,2,3 ......订单的客户数量。

这里有一些可以给你数字的东西,但是没有用过。您需要为o.id

添加正确的列名
Select -- outer query takes each order count and counts how many customers have that many
    co.date_order,
    co.customer_order_count,
    count(*) as customer_count
From (
    Select -- inner query counts how many valid orders each customer has
        o.date_order,
        o.id_customer,
        count(*) as customer_order_count
    From
        customer_order o
    Where
        o.id_credit_order is null and -- rule out credit orders
        not exists ( -- rule out orders with related credit orders
            select
                'x'
            from
                customer_order c
            where
                c.id_credit_order = o.id -- column name isn't mentioned in the question
        )
    Group By
        o.date_order,
        o.id_customer
    ) co
Group By
    co.date_order,
    co.customer_order_count
Order By
    co.date_order desc,
    co.customer_order_count

答案 1 :(得分:0)

尝试使用HAVING子句。

SELECT DATE(co.date_order), COUNT(co.id_customer)
FROM customer_order co
WHERE co.Cancelled = 0
GROUP BY DATE(co.date_order)
HAVING COUNT(co.id_customer) >= 1
ORDER BY DATE(co.date_order) DESC;

答案 2 :(得分:0)

试一试。更改WHERE以反映您取消订单的方式。

SELECT DATE(co.date_order), COUNT(co.id_customer)
FROM customer_order co
WHERE co.cancelled = 0
GROUP BY DATE(co.date_order)
HAVING COUNT(co.id_customer) > 0
ORDER BY DATE(co.date_order) DESC;