[英]SQL Distinct count cumulative
I want to do a query that maps the following input to the following output: 我想做一个查询,将以下输入映射到以下输出:
Input: 输入:
a,b,id
x,y,1
x,y,2
x,z,3
t,z,4
t,y,5
t,y,6
Output: 输出:
count,id
1,1
1,2
2,3
1,4
2,5
2,6
Using the following logic: 使用以下逻辑:
For every different group in a, count how many different b elements are for ids lower or equal than the current id. 对于a中的每个不同组,计算有多少不同的b元素用于id低于或等于当前id。
I have tried: 我努力了:
SELECT COUNT(a), b, id FROM table GROUP BY b
but this doesn't give any cumulative results. 但这并没有给出任何累积结果。
One method is a correlated subquery: 一种方法是相关子查询:
select t.*,
(select count(distinct t2.b) from t t2 where t2.a = t.a and t2.id <= t.id)
from t;
For performance, you want in index on t(a, b)
. 对于性能,您需要在
t(a, b)
上的索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.