CREATE TABLE `test` (
`UniqueID` INT(11) NOT NULL AUTO_INCREMENT,
`Date` date,
`Entry` VARCHAR(20),
PRIMARY KEY (`UniqueID`)
);
INSERT INTO `test` (Date,Entry) VALUES
('2015-09-01','text1'),
('2015-09-01','text1'),
('2015-09-01','text1'),
('2015-09-02','text2'),
('2015-09-02','text2'),
('2015-09-02','text2'),
('2015-09-02','text2'),
('2015-09-03','text3'),
('2015-09-03','text3'),
('2015-09-03','text3'),
('2015-09-04','text4'),
('2015-09-04','text4'),
('2015-09-04','text4'),
('2015-09-04','text4'),
('2015-09-04','text4'),
('2015-09-04','text4');
SET @total:= 0;
SET @prevCount:= 0;
SELECT
@total:= IF (@prevCount <= COUNT(Entry),@total + (COUNT(Entry) - @prevCount),@total) AS total,
@prevCount := COUNT(Entry) AS dayTotal,
`Entry`,
`Date`
FROM test
GROUP BY `Date`
ORDER BY `Date` ASC
| total | dayTotal | Entry | Date |
|-------|----------|-------|-----------------------------|
| 3 | 3 | text1 | September, 01 2015 00:00:00 |
| 4 | 4 | text2 | September, 02 2015 00:00:00 |
| 3 | 3 | text3 | September, 03 2015 00:00:00 |
| 6 | 6 | text4 | September, 04 2015 00:00:00 |
相同的小提琴:http://sqlfiddle.com/#!9/d9031/2
我需要总数不要减少,因为它是随着时间的累积数字。
我的问题似乎是MySQL没有在循环中存储@prevCount - 所以我不能用它来计算总数。
我期望看到的是总计会显示
请注意,7是正确的,因为它是4加上4日的3个新条目。
答案 0 :(得分:0)
使用变量进行计算很棘手。使用group by
,您需要使用子查询。
你的逻辑对我来说并不充分。我能想到的最合理的事情是累计最大值:
SELECT @max := if(@max > dayTotal, @max, dayTotal)
FROM (SELECT `Date`, COUNT(*) as dayTotal
FROM test
GROUP BY `Date`
) t CROSS JOIN
(SELECT @max := 0) params
ORDER BY `Date` ASC;
注意:我删除了Entry
,因为它不在GROUP BY
。