I have the following but I am not getting the correct totals because GROUP BY
does not add the group user id's total revenue.
SELECT
users.id,
Count(orders.id) AS total_orders,
SUM(item_orders.item_price * item_orders.quantity) AS total_rev
FROM
orders
LEFT JOIN
users ON orders.user_id = users.id
LEFT JOIN
item_orders ON item_orders.order_id = orders.id
WHERE
orders.date >= '2015-10-06 00:00:00' AND orders.date <= '2016-03-23 23:59:59'
GROUP BY
users.id -- ignores duplicate ids, doesn't sum total_rev for those
ORDER BY
total_rev DESC
LIMIT 0,25
I would like to use WITH ROLLUP
to solve this but when I use WITH ROLLUP
I can not use ORDER BY
and I can't order with GROUP BY
with an alias which contains my total per user id.
SELECT
users.id,
Count(orders.id) AS total_orders,
SUM(item_orders.item_price * item_orders.quantity) AS total_rev
FROM
orders
LEFT JOIN
users ON orders.user_id = users.id
LEFT JOIN
item_orders ON item_orders.order_id = orders.id
WHERE
orders.date >= '2015-10-06 00:00:00' AND orders.date <= '2016-03-23 23:59:59'
GROUP BY
users.id, total_rev DESC WITH ROLLUP -- does not work because total_rev is an alias!
LIMIT 0,25
Any suggestions on how I can get this to work? Does it make sense I do this in the DB? I am trying to save resources by letting the DB presort so I can do the paging in my application.
EDIT: As xjstratedgebx mentioned in the comments below the first query works fine and there is no reason for using WITH ROLLUP
. The first query can also be shortened like so:
SELECT
orders.user_id,
Count(orders.id) AS total_orders,
SUM(item_orders.item_price * item_orders.quantity) AS total_rev
FROM
orders
LEFT JOIN
item_orders ON item_orders.order_id = orders.id
WHERE
orders.date >= '2015-10-06 00:00:00' AND orders.date <= '2016-03-23 23:59:59'
GROUP BY
orders.user_id
ORDER BY
total_rev DESC
LIMIT 0,25