gpt4 book ai didi

mysql - 累计数字永不减少

转载 作者:行者123 更新时间:2023-11-29 22:01:27 25 4
gpt4 key购买 nike

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 |

同样的 fiddle :http://sqlfiddle.com/#!9/d9031/2

我需要总数字永远不会减少,因为它是随着时间的推移而累积的数字。

我的问题似乎是 MySQL 没有在循环中存储 @prevCount - 所以我无法使用它来计算总数。

我期望看到的是总计将显示

  1. 3
  2. 4
  3. 4
  4. 7

请注意,7 是正确的,因为它是 4 加上 4 日的 3 个新条目。

最佳答案

使用变量进行计算很棘手。使用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 中。

关于mysql - 累计数字永不减少,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32612797/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com