myql:总结每家商店每天的销售总额

时间:2017-10-11 12:30:19

标签: mysql

表格是:

mysql> DESC sell_data;
+------------+--------------+------+-----+---------------------+----------------+
| Field      | Type         | Null | Key | Default             | Extra          |
+------------+--------------+------+-----+---------------------+----------------+
| id         | int(64)      | NO   | PRI | NULL                | auto_increment |
| name       | varchar(128) | NO   |     |                     |                |
| sell_date  | datetime     | NO   |     | 0000-00-00 00:00:00 |                |
| sell_price | double       | YES  |     | NULL                |                |
| cost       | double       | NO   |     | 0                   |                |
| store_id   | int(11)      | NO   |     | 0                   |                |
+------------+--------------+------+-----+---------------------+----------------+

我将表结构附加为图片,看起来编辑器确实支持格式。

此表中有100条记录,并要求在每个商店的给定周内总结每一天的销售总额,这意味着对于每个给定的商店ID,需要7个小计,结果如下:

store 1: 122  123  124  125  126  127  128
store 2: 131  122  133  134  135  136  137

...

这对我来说非常困难,请求帮助,非常有吸引力。 :)

我尝试按“GROUP BY”对数据进行分组,如:

SELECT store_id
     , SUM(cost) AS all_cost
     , SUM(sell_price) AS all_price 
FROM sell_data 
WHERE sell_date BETWEEN '2017-10-12' AND '2017-10-15' 
GROUP BY store_id;

但它只提供每个商店的总和数据,而不是每天的数据,完全停留在这里。

3 个答案:

答案 0 :(得分:1)

在我看来你需要一个数据透视查询。 这是通过将GROUP BY与SUM和CASE

结合使用来完成的
SELECT
   SUM(
     CASE
      WHEN DAYNAME(sell_date) = 'Monday'
      THEN sell_price
      ELSE 0 
    END 
   ) 
    AS 
     Monday
 , SUM(
     CASE
      WHEN DAYNAME(sell_date) = 'Tuesday'
      THEN sell_price
      ELSE 0 
    END 
 ) 
  AS 
   Tuesday
 , SUM(
     CASE
      WHEN DAYNAME(sell_date) = 'Wednesday'
      THEN sell_price
      ELSE 0 
    END 
 ) 
  AS 
   Wednesday
 , SUM(
     CASE
      WHEN DAYNAME(sell_date) = 'Thursday'
      THEN sell_price
      ELSE 0 
    END 
 ) 
  AS 
   Thursday
 , SUM(
     CASE
      WHEN DAYNAME(sell_date) = 'Friday'
      THEN sell_price
      ELSE 0 
    END 
 ) 
  AS 
   Friday
 , SUM(
     CASE
      WHEN DAYNAME(sell_date) = 'Saturday'
      THEN sell_price
      ELSE 0 
    END 
 ) 
  AS 
   Saturday
 , SUM(
     CASE
      WHEN DAYNAME(sell_date) = 'Sunday'
      THEN sell_price
      ELSE 0 
    END 
 ) 
  AS 
   Sunday
FROM 
 [table]
WHERE
 WEEK(sell_date) = [week_number]
GROUP BY 
 store_id
ORDER BY 
 store_id ASC

答案 1 :(得分:0)

你需要

 group by store_id, date(sell_date) 

您可能希望将其添加到您的选择

答案 2 :(得分:-1)

使用sum(sell_price)与group by store_id