gpt4 book ai didi

mysql - mysql查询中组计数的累计和

转载 作者:可可西里 更新时间:2023-11-01 07:26:20 24 4
gpt4 key购买 nike

我有一个如下所示的表格....

ID HID  Date          UID
1 1 2012-01-01 1002
2 1 2012-01-24 2005
3 1 2012-02-15 5152
4 2 2012-01-01 6252
5 2 2012-01-19 10356
6 3 2013-01-06 10989
7 3 2013-03-25 25001
8 3 2014-01-14 35798

我如何按 HID、年、月和计数 (UID) 分组并添加 cumulative_sum(这是 UID 的计数)。所以最后的结果看起来像这样......

HID  Year   Month   Count  cumulative_sum
1 2012 01 2 2
1 2012 02 1 3
2 2012 01 2 2
3 2013 01 1 1
3 2013 03 1 2
3 2014 01 1 3

使用查询完成此操作的最佳方法是什么?

最佳答案

我对原始数据集做了假设。您应该能够使它适应修改后的数据集 - 尽管请注意使用变量的解决方案(而不是我的自连接)更快......

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(ID INT NOT NULL
,Date DATE NOT NULL
,UID INT NOT NULL PRIMARY KEY
);

INSERT INTO my_table VALUES
(1 ,'2012-01-01', 1002),
(1 ,'2012-01-24', 2005),
(1 ,'2012-02-15', 5152),
(2 ,'2012-01-01', 6252),
(2 ,'2012-01-19', 10356),
(3 ,'2013-01-06', 10989),
(3 ,'2013-03-25', 25001),
(3 ,'2014-01-14', 35798);


SELECT a.*
, SUM(b.count) cumulative
FROM
(
SELECT x.id,YEAR(date) year,MONTH(date) month, COUNT(0) count FROM my_table x GROUP BY id,year,month
) a
JOIN
(
SELECT x.id,YEAR(date) year,MONTH(date) month, COUNT(0) count FROM my_table x GROUP BY id,year,month
) b
ON b.id = a.id AND (b.year < a.year OR (b.year = a.year AND b.month <= a.month)
)
GROUP
BY a.id, a.year,a.month;
+----+------+-------+-------+------------+
| id | year | month | count | cumulative |
+----+------+-------+-------+------------+
| 1 | 2012 | 1 | 2 | 2 |
| 1 | 2012 | 2 | 1 | 3 |
| 2 | 2012 | 1 | 2 | 2 |
| 3 | 2013 | 1 | 1 | 1 |
| 3 | 2013 | 3 | 1 | 2 |
| 3 | 2014 | 1 | 1 | 3 |
+----+------+-------+-------+------------+

如果您不介意在结果中增加一列,您可以简化(并加速)上述操作,如下所示:

SELECT x.*
, @running:= IF(@previous=x.id,@running,0)+x.count cumulative
, @previous:=x.id
FROM
( SELECT x.id,YEAR(date) year,MONTH(date) month, COUNT(0) count FROM my_table x GROUP BY id,year,month ) x
,( SELECT @cumulative := 0,@running:=0) vals;

关于mysql - mysql查询中组计数的累计和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25807194/

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