this answer的第二部分使用变量来创建另一列的累积和.我正在做同样的事情,除了我使用GROUP BY语句,并且总结COUNT(*)而不是列.这是我创建最小表和插入值的代码:
CREATE TABLE `test_group_cumulative` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`group_id` int(11) unsigned NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `test_group_cumulative` (`id`, `group_id`)
VALUES
(1, 1),
(2, 2),
(3, 3);
以下是失败的代码:
SELECT
`group_id`,
COUNT(*) AS `count`,
@count_cumulative := @count_cumulative + COUNT(*) AS `count_cumulative`
FROM `test_group_cumulative` AS `tgc`
JOIN (SELECT @count_cumulative := 0) AS `_count_cumulative`
GROUP BY `group_id`
ORDER BY `id`;
结果如下