如何从连接列按年份分组

How to group by year from a concatenated column

有一个 MySQL table ,其中 id 是日期与 Ymd 格式的串联(插入行的那一刻) 带有增量 ID。

|     id      |   weight  |
| 20200128001 |    100    |
| 20200601002 |    250    |
| 20201208003 |    300    |
| 20210128001 |    150    |
| 20210601002 |    200    |
| 20211208003 |    350    |

要按一年计算 'weight' 的总和:

SELECT sum(weight) as weight FROM `table` WHERE id LIKE '2020%';

在这种情况下结果为:

650

我怎样才能使它按年产生 table 个权重,而不是按每个可能的年份进行查询,在这种情况下会导致:

| date |  weight  |
| 2020 |    650   |
| 2021 |    700   |

使用 MySQL 中的字符串处理函数之一,例如 left()

SELECT LEFT(id,4) as Year, SUM(weight) as Weight
FROM `table`
GROUP BY LEFT(id,4)
ORDER BY LEFT(id,4)

如果您想将结果限制在这 2 年内

SELECT LEFT(id,4) as Year, SUM(weight) as Weight
FROM `table`
WHERE LEFT(id,4) IN (2021, 2022)
GROUP BY LEFT(id,4)
ORDER BY LEFT(id,4)