[英]Find 3 or more consecutive transaction record where the transaction amount greater than 100 and the records belong to the same category
I have a customer transaction table which has 3 columns, id, Category, TranAmount.我有一个客户交易表,它有 3 列,id、Category、TranAmount。 Now I want to find 3 or more consecutive transaction records which belongs to the same category and the TranAmount greater than 100. Below is the sample table:现在我想找到 3 个或更多属于同一类别且 TranAmount 大于 100 的连续交易记录。以下是示例表:
Id Category TranAmount
1 A 190
2 A 160
3 A 169
4 B 190
5 A 90
6 B 219
7 B 492
8 B 129
9 B 390
10 B 40
11 A 110
12 A 130
And the output should be:输出应该是:
Id Category TranAmount
1 A 190
2 A 160
3 A 169
6 B 219
7 B 492
8 B 129
9 B 390
Look into "gaps and islands" reference for a deeper understanding of the approach.查看“差距和孤岛”参考以更深入地了解该方法。 Here's one of many you could read: https://www.red-gate.com/simple-talk/sql/t-sql-programming/the-sql-of-gaps-and-islands-in-sequences/这是您可以阅读的众多内容之一: https : //www.red-gate.com/simple-talk/sql/t-sql-programming/the-sql-of-gaps-and-islands-in-sequences/
In this specific problem you have two conditions that cause a break in a consecutive series, those being a change in category or an amount that doesn't meet the threshold.在此特定问题中,您有两个条件会导致连续系列中断,即类别更改或金额不符合阈值。
with data as (
select *,
row_number() over (order by Id) as rn,
row_number() over (partition by
Category, case when TranAmount >= 100 then 1 else 0 end order by Id) as cn
from Transactions
), grp as (
select *, count(*) over (partition by rn - cn) as num
from data
where TranAmount >= 100
)
select * from grp where num >= 3;
https://rextester.com/DUM44618 https://rextester.com/DUM44618
I can't really test this out yet but give this a try.我还不能真正对此进行测试,但请尝试一下。
SELECT Id, Category, Amount FROM Table
WHERE Amount > 100
and Category IN
(SELECT Category FROM Table
WHERE Amount > 100
GROUP BY Category HAVING COUNT (Category ) >= 3)
This will work if there are no gaps between the ids:如果 id 之间没有间隙,这将起作用:
select distinct t.*
from tablename t inner join (
select t.id from tablename t
where t.tranamount > 100
and
exists (
select 1 from tablename
where id = t.id - 1 and category = t.category and tranamount > 100
)
and
exists (
select 1 from tablename
where id = t.id + 1 and category = t.category and tranamount > 100
)
) tt on t.id in (tt.id - 1, tt.id, tt.id + 1)
See the demo .请参阅演示。
Results:结果:
Id | Category | TranAmount
-: | :------- | ---------:
1 | A | 190
2 | A | 160
3 | A | 169
6 | B | 219
7 | B | 492
8 | B | 129
9 | B | 390
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.