0

我想知道有多少客户下了超过 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;
4

3 回答 3

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
于 2013-09-06T20:15:48.757 回答
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;
于 2013-09-06T20:07:57.640 回答
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;
于 2013-09-06T20:04:23.807 回答