【发布时间】:2021-05-31 05:52:33
【问题描述】:
我在 MySQL 数据中有下表
CREATE TABLE `new_table` (
`date1` varchar(20) DEFAULT NULL,
`organisation` varchar(45) DEFAULT NULL,
`proportion` varchar(45) DEFAULT NULL,
`id` int NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `new_table` (`date1`, `organisation`, `proportion`) VALUES ('7/31/2020', 'Clinical Services', '50');
INSERT INTO `new_table` (`date1`, `organisation`, `proportion`) VALUES ('7/31/2020', 'Data and analytics', '60');
INSERT INTO `new_table` (`date1`, `organisation`, `proportion`) VALUES ('8/31/2020', 'Clinical Services', '12');
INSERT INTO `new_table` (`date1`, `organisation`, `proportion`) VALUES ('8/31/2020', 'Data and analytics', '40');
INSERT INTO `new_table` (`date1`, `organisation`, `proportion`) VALUES ('9/30/2020', 'Clinical Services', '25');
INSERT INTO `new_table` (`date1`, `organisation`, `proportion`) VALUES ('9/30/2020', 'Data and analytics', '20');
我想通过date1分别得到date1和proportion组的总和,分别为opening和closing,条件如下
- 如果存在上个月的数据,则上个月的
SUM(proportion)为当月的opening,当月的SUM(proportion)为closing。 - 当上个月的数据不存在时,
SUM(proportion)是当月的开盘。
结果表应该是
| Date | opening | closing |
|---|---|---|
| 7/31/2020 | 110 | 110 |
| 8/31/2020 | 110 | 52 |
| 9/20/2020 | 52 | 45 |
我正在使用以下查询
SELECT
date1 as 'Date',
CASE
WHEN (
SELECT
SUM(proportion)
FROM
new_table
WHERE
MONTH(str_to_date(date1, '%m/%d/%Y')) = MONTH(str_to_date(date1, '%m/%d/%Y')) - 1
GROUP BY date1
LIMIT 1
) > 0
THEN (
SELECT
SUM(proportion)
FROM new_table
WHERE
MONTH(str_to_date(date1, '%m/%d/%Y')) = MONTH(str_to_date(date1, '%m/%d/%Y')) - 1
GROUP BY date1
LIMIT 1
)
ELSE (
SELECT
sum(proportion)
FROM new_table
WHERE
MONTH(str_to_date(date1, '%m/%d/%Y')) = MONTH(str_to_date(date1, '%m/%d/%Y'))
GROUP BY date1
LIMIT 1
)
END as 'Opening',
SUM(proportion) as 'Closing'
FROM new_table
GROUP BY date1
但它给出了以下输出,其中Opening 对于所有行都是相同的。
示例:https://paiza.io/projects/Jgbxf3Xxag8fKIb3OuasjA?language=mysql
【问题讨论】:
-
您使用的是哪个版本的 MySQL?请您以文本格式分享示例数据。
-
我已经用示例数据和编辑器更新了问题。
-
@Strawberry 如果您的意思是
date1列,那么实际上使用的数据源具有 VARCHAR 列。我无权修改它。 -
为什么
Closing的最后一个日期是 45 而 24+35=59? -
@Akina 这个问题是由某人使用导致不匹配的示例数据编辑的。我已经更新了问题中的相同数据。