产品销售报告每周一次

时间:2012-10-21 07:30:53

标签: php mysql sql

如何运行SQL查询来检索每周和每月的销售报告。

表:订单

ID | Product_id |订单价格|数量|购买日期

1        1           34         2        9/10/12
2        1           34         2        8/10/12
3        4           34         2        07/10/12
4        3           34         2        22/09/12
5        1           34         2        9/10/12
6        1           34         2        22/09/12
7        4           34         2        9/08/12
8        3           34         2        22/09/12

表:产品

ID | Name | description

1    A       ksfjsdkf
2    B       ksfjsdkf
3    C       ksfjsdkf
1    A       ksfjsdkf

期待结果 :以下是一个不准确的示例结果

product_name           Weekly Sum(QTY), weekly revenue,  Monthly SUM(QTY), monthly revenue

A                           120             3000           2345                  234343

3 个答案:

答案 0 :(得分:2)

这里有一个简单的数量和订单价格查询

SELECT p.Description, psw.qtysum, psw.opsum, psm.qtysum, psm.opsum
FROM Products p
LEFT JOIN
  ( SELECT sw.product_id, SUM( sw.QTY ) AS qtysum, SUM( sw.`order price` ) AS opsum 
    FROM orders sw 
    WHERE WEEK( sw.`purchase date`) = WEEK( current_date )
    AND YEAR( sw.`purchase date`) = YEAR( current_date )
    GROUP BY sw.product_id ) psw 
  ON p.id = psw.product_id

LEFT JOIN
  ( SELECT sm.product_id, SUM( sm.QTY ) AS qtysum, SUM( sm.`order price` ) AS opsum 
    FROM orders sm 
    WHERE MONTH( sm.`purchase date`) = MONTH( current_date )
    AND YEAR( sm.`purchase date`) = YEAR( current_date )
    GROUP BY sm.product_id ) psm 
  ON p.id = psm.product_id

答案 1 :(得分:0)

您可以使用php datetime(“W”)获取weeknumber和datetime(“m”)来获取月份数,然后将数据库中的所有日期转换为weeknumber和monthnumber并对其进行排序。

答案 2 :(得分:0)

SELECT p.name, week.qty, week.price, month.qty, month.price
FROM products p LEFT JOIN
  (SELECT p.id AS prod_id, SUM(o.qty) AS qty, SUM(o.price) AS price
   FROM products p LEFT JOIN orders o ON p.id = o.prod_id
   WHERE o.date >= DATE_SUB(CURDATE(), INTERVAL 7 day)
   GROUP BY p.id) AS week ON p.id = week.prod_id LEFT JOIN
  (SELECT p.id AS prod_id, SUM(o.qty) AS qty, SUM(o.price) AS price
   FROM products p LEFT JOIN orders o ON p.id = o.prod_id
   WHERE o.date >= DATE_SUB(CURDATE(), INTERVAL 1 month)
   GROUP BY p.id) AS month ON p.id = month.prod_id

没有太优化,但我没有这里的mysql cli所以我不会发布任何更复杂的东西,如果没有能力测试,甚至可能无法工作。