如何从表中聚合数据,以显示基于类别的产品总数(使用每个月作为键)

jgovgodb  于 2021-06-24  发布在  Mysql
关注(0)|答案(3)|浏览(297)
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');

我的sql小提琴:http://sqlfiddle.com/#!9/4ff0cf/1/0结果应该是这样的。

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

如果你注意到,附件有一月份的多个条目,它是总和。
如果可以的话,请在你的答案中加入一个sql fiddle。谢谢。

yws3nbqq

yws3nbqq1#

试试这个:

select datepurchased month, productcategory, sum(productprice) amount
from products
group by datepurchased, productcategory
order by datepurchased, amount desc;

请参阅SQLFiddle上的工作演示。

f5emj3cl

f5emj3cl2#

由于datepurchased列不是date或datetime列,因此需要使用特定的字符串函数对其进行操作。
这是你的答案,希望对你有帮助。任何问题,请告诉我。

SELECT
      cte._month
      , cte.productcategory
      , SUM(cte.productprice) AS totalPrice
    FROM (
            SELECT
                id
                ,productname
                ,productcategory
                ,productprice
                ,CAST(SUBSTRING_INDEX(datepurchased, ' ', 1) AS UNSIGNED) AS _year
                ,TRIM(SUBSTRING(datepurchased, POSITION(' ' IN datepurchased), (LENGTH(datepurchased) - 
                            LENGTH(SUBSTRING_INDEX(datepurchased, ' ', 1)))
                            )) AS _month
            FROM products
    ) AS cte
    GROUP BY cte._month, cte.productcategory;

sql FIDLE url:http://sqlfiddle.com/#!9/4ff0cf/43号

3mpgtkmj

3mpgtkmj3#

在这里摆弄:http://sqlfiddle.com/#!9/4ff0cf/15/0号
您要做的是使用多个参数进行分组:

SELECT id, productcategory, sum(productprice), datepurchased FROM
products GROUP BY productcategory, datepurchased;

相关问题