简体   繁体   中英

How to get Sale data of every month of a year

I'm trying to get Sale Data of every month of particular year, but I'm having a problem building a query for it.

Here is What I've tried

SELECT COUNT(`id`) AS `total_order`
FROM orders
WHERE date BETWEEN ? AND ?
GROUP BY `total_order`

HERE is How my table look like

----------------------------------------
| id | item_name | amount | time       |
| 21 | item_1    | 10     | 1506675630 |
| 22 | item_2    | 30     | 1506675630 |
| 23 | item_3    | 70     | 1506675630 |
| 24 | item_4    | 100    | 1506675630 |
----------------------------------------

Now here is what i want from the query

1 - Total Sales amount made from the beginning of the year till today.
2 - Sales made Today
3 - Sales made in Last Month
4 - Sales Made in Last 3 month
5 - Sales Made in Last 6 Month
6 - Total Number of Sales made in every month of this particular year

for eg - January - 20 Feb -100 March - 200 & so on.

How can i achieve this complex query?

    SELECT `id` AS `Order_Number`, item_name, SUM(Amount)
    FROM orders
    WHERE time >= '01/01/17'
    GROUP BY date

That would give you your first result. Try the others and let me know what you get

This answers your first question

SELECT
DATE_FORMAT(FROM_UNIXTIME(time), '%Y-%m') as interval,
COUNT(*) AS sales_made,
SUM(amount) AS sales_amount
FROM orders
WHERE
time BETWEEN UNIX_TIMESTAMP('2017-01-01') AND UNIX_TIMESTAMP('2018-01-01')
GROUP BY 1
ORDER BY 1;

Here is what i think would work:

for the first 5 queries try something like this.

SELECT SUM(amount)
    FROM orders
    WHERE DATE_FORMAT(FROM_UNIXTIME(`orders.time`), '%Y-%m-%d') BETWEEN ? AND ?

And for the last one you'll need :

SELECT DATE_FORMAT(FROM_UNIXTIME(`orders.time`), '%Y-%m-%d') AS 'date', SUM(amount)
        FROM orders
        WHERE date between ? AND ?
        GROUP BY DATE_FORMAT(date, '%Y%m')

You can try without the FROM_UNIXTIME if it doesnt work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM