I’ve been writing MySQL queries for a long time, but I totally feel like a newbie when it comes to this and I just can’t seem to figure out how to simplify this query. Basically I’m just trying to generate a comma delimited list of revenue from our database that eventually gets plugged into google charts. I have to make one for “the past 31 days” also, so I’m kinda screwed unless I figured out how to simplify this.
My Database columns in my table are…
- time: When the order came in int() (UNIX timestamp format)
- price: How much the order was for decimal(10,2)
SELECT
CONCAT(
(SELECT SUM(price) FROM orders WHERE time < (UNIX_TIMESTAMP() - (6 * 86400)) AND time > (UNIX_TIMESTAMP() - (7 * 86400))),
',',
(SELECT SUM(price) FROM orders WHERE time < (UNIX_TIMESTAMP() - (5 * 86400)) AND time > (UNIX_TIMESTAMP() - (6 * 86400))),
',',
(SELECT SUM(price) FROM orders WHERE time < (UNIX_TIMESTAMP() - (4 * 86400)) AND time > (UNIX_TIMESTAMP() - (5 * 86400))),
',',
(SELECT SUM(price) FROM orders WHERE time < (UNIX_TIMESTAMP() - (3 * 86400)) AND time > (UNIX_TIMESTAMP() - (4 * 86400))),
',',
(SELECT SUM(price) FROM orders WHERE time < (UNIX_TIMESTAMP() - (2 * 86400)) AND time > (UNIX_TIMESTAMP() - (3 * 86400))),
',',
(SELECT SUM(price) FROM orders WHERE time < (UNIX_TIMESTAMP() - 86400) AND time > (UNIX_TIMESTAMP() - (2* 86400)) ),
',',
(SELECT SUM(price) FROM orders WHERE time > (UNIX_TIMESTAMP() - 86400))
) as chart_rev
FROM orders_basic
LIMIT 0,1
If possible, I need it in 24 hour increments like this.
As always, any help is much appreciated. Thanks!
SOLUTION
Please note: Look carefully at your results, they may be there, just in the wrong order, if so, reverse your sorting.
SELECT GROUP_CONCAT(total_sum) AS sum_list FROM
(
SELECT
FLOOR((UNIX_TIMESTAMP() - time) / 86400) AS date,
SUM(price) AS total_sum
FROM
orders_basic
WHERE
is_testorder < 1
AND FROM_UNIXTIME(time) > DATE_SUB(NOW(), INTERVAL 1 WEEK)
GROUP BY
date
) AS s
Something like this maybe?
This should give you a comma separated list of last month sale sums. But it will group on the date, not 24 hour increments (so cutoff will be midnight, according to the
timecolumn).