Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Group Results by day using timestamp

I need to take the following query and pull the total order counts and sum of the orders grouped by day. I'm storing everything using timestamps.

SELECT     COUNT(id) as order_count,     SUM(price + shipping_price) as order_sum,     DAY(FROM_UNIXTIME(created)) as day FROM `order` WHERE '.implode(' AND ', $where).' 

I need to group by DAY but when I do for this past weekend's sales it takes my order_count and makes it 1 instead of 3. How can I pull the above values grouped by day?

NOTE: The implode is used ONLY to define the time period (WHERE created >= TIMESTAMP AND <= TIMESTAMP)

Update

Without GROUP BY day

Array (      [order_count] => 3     [order_sum] => 69.70     [day] => 17 ) 

With GROUP BY day

Array (      [order_count] => 1     [order_sum] => 24.90     [day] => 17 ) 

I need this query to return each day that had sales, how many orders, and the sum of those sales. I'm missing a piece of the puzzle here somewhere....

like image 646
Webnet Avatar asked Apr 19 '10 21:04

Webnet


People also ask

Does Datepart work in MySQL?

Does Datepart work in MySQL? There is no DATEPART function in MySQL. Use MONTH(date_column) or EXTRACT(MONTH FROM date_column) instead.

How does timestamp work in MySQL?

MySQL converts TIMESTAMP values from the current time zone to UTC for storage, and back from UTC to the current time zone for retrieval. (This does not occur for other types such as DATETIME .) By default, the current time zone for each connection is the server's time.

What is Unix_timestamp in MySQL?

UNIX_TIMESTAMP() : This function in MySQL helps to return a Unix timestamp. We can define a Unix timestamp as the number of seconds that have passed since '1970-01-01 00:00:00'UTC. Even if you pass the current date/time or another specified date/time, the function will return a Unix timestamp based on that.


1 Answers

Are you just forgetting to add GROUP BY ... at the end?

SELECT     COUNT(id) as order_count,     SUM(price + shipping_price) as order_sum,     DAY(FROM_UNIXTIME(created)) as order_day FROM `order` WHERE '.implode(' AND ', $where).' GROUP BY order_day 

NOTE:

You cannot use as day for your day column because day is a MySQL function. Use something like order_day.

Of Unicorns

Per @OMG Unicorn's comment, you can use:

DAY(FROM_UNIXTIME(created)) as `day` 

So long as wrap day in ` backticks.

like image 63
maček Avatar answered Oct 02 '22 08:10

maček