php - How do i aggregate data from a table to show the sum of products based on the category using each month as key
问题描述
create table products
(
id int not null,
productname varchar(45),
productcategory varchar(45),
productprice decimal(8,2),
datepurchased varchar(45),
primary key (id)
);
INSERT INTO products (id, productname, productcategory, productprice, datepurchased) VALUES
(1, 'Toy car', 'toys', 200.30, '2017 December'),
(2, 'Phone', 'phone', 50.00, '2017 December'),
(3, 'Disk drive', 'Accessories', 10.00, '2018 January'),
(4, 'Mouse', 'Accessories', 20.30, '2018 January'),
(5, 'Baby doll', 'toys', 100.00, '2018 February'),
(6, 'Toy car', 'toys', 40.10, '2018 March');
My sql fiddle: http://sqlfiddle.com/#!9/4ff0cf/1/0 The results should look like this.
Month | ProductCategory | Amount
-------------------------------------------------
2017 December | toys | 200.30
2018 January | phone | 50.00
2018 January | Accessories | 30.30
2018 February | toys | 100.00
2018 March | toys | 40.10
If you notice, Accessories has multiple entries for January and it is summed.
Please include a sql fiddle in your answer if you can. Thanks.
解决方案
Fiddle here: http://sqlfiddle.com/#!9/4ff0cf/15/0
What you want is to do a group by with multiple params:
SELECT id, productcategory, sum(productprice), datepurchased FROM
products GROUP BY productcategory, datepurchased;
推荐阅读
- python - Pandas:如何仅删除列末尾的最后一个连字符
- google-forms - 如何根据其他用户过去的回复使 Google 表单自动填充?
- c - 我知道一个地址,但我应该如何判断在哪个部分?使用C的全局区域或堆区域或堆栈区域
- json - 如何解决“手势 RangeError(索引)捕获的异常:无效值:有效值范围为空:0”
- c++ - 什么会使多边形算法中的点仅在正向和反向运行时才能正常工作?
- php - PHP:如何使用键->值对每两个分隔符将一个字符串分解为一个数组
- kubernetes - 将 GKE 集群拆除为“全新”状态而不删除它?
- scala - Spark——自定义reduce函数保存到磁盘然后上传到s3
- javascript - XMLHttpRequest 返回事件对象而不是实际数据
- fortran - Fortran 将未知大小的文件读入数组