Mysql检索最近30天的数据并按天计算

时间:2017-05-01 11:36:47

标签: mysql

我希望每天在商店中对所有过去30天的购买进行分组,并返回最近30天的以下数据数组,例如

2017/04/01
purchases: 30
total: 900.01

2017/04/02
purchases: 30
total: 900.01

等等。到目前为止,我不知道如何进行这种查询,并提出了以下想法

    SELECT COALESCE(SUM(purchases.price)/1000,0) AS all_purchases, 
    min(purchases.time) AS start_interval, max(purchases.time) AS end_interval
    FROM purchases
    WHERE purchases.time::date >= DATE_SUB(NOW(), INTERVAL 30 DAY) AND WHERE purchases.time::date <= DATE_SUB(NOW())
    ORDER BY start_interval DESC

但这不是它的运作方式

1 个答案:

答案 0 :(得分:3)

你应该使用group by ::

  SELECT date(purchases.time) as my_date ,  count(*) as my_count, 
          COALESCE(SUM(purchases.price)/1000,0) AS all_purchases
  FROM purchases
  WHERE date(purchases.time) >= DATE_SUB(CURDATE(), INTERVAL 30 DAY) 
         AND   date(purchases.time) <= CURDATE()
  GROUP BY date(purchases.time)
  ORDER BY my_date DESC

(你应该只使用一次..不在哪里..而在哪里但是......和......)