如何获得一年中每个月的销售数据

时间:2017-09-29 09:06:32

标签: php mysql sql

我试图获取特定年份每个月的销售数据,但我在构建查询时遇到问题。

以下是我尝试过的内容

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

这是我的表格如何

----------------------------------------
| 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 |
----------------------------------------

现在这是我想要的查询

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

例如 - 1月20日 2月-100 三月 - 200&等等。

如何实现这种复杂的查询?

3 个答案:

答案 0 :(得分:0)

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

那会给你第一个结果。尝试其他人,让我知道你得到了什么

答案 1 :(得分:0)

这回答了你的第一个问题

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;

答案 2 :(得分:0)

以下是我认为可行的方法:

对于前5个查询尝试这样的事情。

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

对于你需要的最后一个:

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')

如果它不起作用,你可以在没有FROM_UNIXTIME的情况下尝试。