简体   繁体   中英

Sql cumulative count with two variables

I have a table with three columns: a, b, and id.

I want to find, using sql, for every id, the number of equal (a, b) pairs with ids lower than the given id. For this reason, the approach can be explained as doing a cumulative count of the pairs (a, b) when the sql table is sorted by id.

I don't really know how to implement this using sql syntax. Can you provide some advise, please?


What I've tried and doesn't work:

SELECT count(*), a, b, id FROM table GROUP BY a, b

Doesn't really give any cumulative results and shows grouped index results, so I am not interested in that and I don't know how to modify it.

Example: Input:

a,b,id    
x,y,1    
x,y,2    
x,z,3    
t,y,4    
t,y,5

Output:

count,id

1,1
2,2
1,3
1,4
2,5

Use a subquery in your select clause. I assume you want to count as follows:

select
  (select count(*) from mytable m2 where m2.id < m1.id and m2.a = m1.a and m2.b = m1.b)
    as cnt,
  id
from mytable m1
order by id;

As of MySQL 8.0 you can do this a little more elegantly with a window clause:

select count(*) over (partition by a, b order by id) as cnt, id
from mytable m1
order by id;

You can use the Distinct tag to limit to the unique pairs returned in the query.

Select t.id, count(*) from
    (Select Distinct id, a, b
       From &table
      Where id < &id) t
Group by id;

You can use subquery :

select t.id,
       (select count(*)
        from table t1
        where t1.a = t.a and t1.b = t.b and
              t1.id <= t.id
       ) as cnt
from table t;

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