简体   繁体   中英

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.


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) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM