[英]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.