【发布时间】:2021-05-29 06:34:55
【问题描述】:
我用不同年份的销售数据创建了mysqltable。link to sql fiddle
我想在表格中有一列显示今年的销售额,另外一列显示去年的销售额总和,如图所示。
CREATE TABLE agreement (
Id INT NOT NULL,
supplier VARCHAR(25) NOT NULL,
sales VARCHAR(25) NOT NULL,
yearDate DATE NOT NULL,
yearx VARCHAR(10)
);
INSERT INTO agreement
(Id, supplier, sales, yeardate,yearx)
VALUES
('1', 'AB Foods', '2', '2020-01-01', '2020'),
('2', 'BC Foods', '2', '2020-01-01','2020'),
('11', 'AB Foods', '34', '2020-02-01', '2020'),
('22', 'BC Foods', '80', '2020-02-01','2020'),
('5', 'AB Foods', '5', '2021-01-03','2021'),
('6', 'BC Foods', '5', '2021-01-03','2021'),
('52', 'AB Foods', '51', '2021-02-03','2021'),
('16', 'BC Foods', '50', '2021-02-03','2021')
;
我解决问题的方法:
SELECT
supplier,
yearx,
sum(if(month(yearDate) = 1, sales, 0)) AS Jan,
sum(if(month(yearDate) = 2, sales, 0)) AS Feb,
sum(sales) AS Total_ThisYear,
sum(sales) AS Total_LaastYear
FROM agreement
GROUP BY supplier, yearx
order by yearx
但似乎我需要在 case 语句中添加 where 子句。
提前谢谢你
【问题讨论】:
-
您可以发布您的查询吗?
-
@Strawberry 它包含在上面已经提到的链接中sqlfiddle.com/#!9/9ce3aa/4
-
考虑处理应用代码中数据显示的问题
标签: mysql join html-table phpmyadmin pivot-table