开发者

MySQL Group Results by day using timestamp

开发者 https://www.devze.com 2022-12-27 16:28 出处:网络
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.

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
   开发者_如何学Python [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....


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.


You could also simply use:

SELECT 
COUNT( id ) AS order_count, 
SUM( price + shipping_price ) AS order_sum
FROM  `order` 
GROUP BY LEFT( timestamp, 10 ) 

or even

GROUP BY SUBSTR( timestamp, 1, 10 )


You're probably running into a naming conflict between DAY() (the function in MySQL) and day (your variable name). Have you tried using something that wont conflict such as order_day?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号