繁体   English   中英

带两个变量的SQL累积计数

[英]Sql cumulative count with two variables

我有一个包含三列的表:a,b和id。

我想使用sql查找每个id,其id小于给定id的相等(a,b)对的数量。 因此,该方法可以解释为对sql表按id排序时,对(a,b)进行累加计数。

我真的不知道如何使用sql语法实现这一点。 您能提供一些建议吗?


我尝试过但不起作用的内容:

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

实际上并没有给出任何累积结果,也不显示分组索引结果,因此我对此不感兴趣,也不知道如何修改它。

示例:输入:

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

输出:

count,id

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

在您的select子句中使用子查询。 我假设您要计算如下:

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;

从MySQL 8.0开始,您可以使用window子句更优雅地做到这一点:

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

您可以使用Distinct标记来限制查询中返回的唯一对。

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

您可以使用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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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