0

如何运行 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
4

3 回答 3

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
于 2012-10-21T08:07:40.197 回答
0

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

于 2012-10-21T07:45:47.140 回答
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,所以我不会发布任何没有能力测试甚至可能无法工作的复杂内容。

于 2012-10-21T08:00:46.943 回答