我正在寻找一个查询,该查询将为我提供按订购数量分组的订单数量,以及我希望获得这些数量的收入。
例如。
| Number of Orders | Numbers of Customers | Revenue Of Orders |
| 1 | 312 | 4350.88 |
| 2 | 208 | 3490.00 |
| 3 | 152 | 2240.50 |
我的前两列工作正常。这就是该查询
SELECT
r.num_of_orders ,
count(*) AS num_of_customers
FROM
(
SELECT
count(*) AS num_of_orders
FROM
reservations r
WHERE
created_at >= '2008-01-01 00:00:00'
AND `status` = 'closed'
GROUP BY
r.customer_id
) r
GROUP BY
r.num_of_orders
尝试增加我尝试过的收入。
SELECT
r.num_of_orders ,
count(*) AS num_of_customers,
sum(b.total) as total_revenue
FROM
(
SELECT
count(*) AS num_of_orders
FROM
reservations r
WHERE
created_at >= '2008-01-01 00:00:00'
GROUP BY
r.customer_id
) r,
(
SELECT
sum(payments.total) AS total
FROM
reservations r
JOIN payments ON payments.id = r.reservation_id
WHERE
r.created_at >= '2008-01-01 00:00:00'
GROUP BY
r.customer_id
) b
GROUP BY
r.num_of_orders
但是我知道这些收入数字已经消失了。.
希望您能提供建议。
答案 0 :(得分:0)
将其添加到原始子查询中:
SELECT r.num_of_orders, count(*) AS num_of_customers,
SUM(revenue) as total_revenue
FROM (SELECT COUNT(DISTINCT r.reservation_id) AS num_of_orders,
SUM(p.total) as revenue
FROM reservations r JOIN
payments p
ON p.id = r.reservation_id
WHERE r.created_at >= '2008-01-01' AND
r.status = 'closed'
GROUP BY r.customer_id
) r
GROUP BY r.num_of_orders;