![](/img/trans.png)
[英]SQL query to display the records which have 3 or more consecutive rows and the amount of people more than 100
[英]Find 3 or more consecutive transaction record where the transaction amount greater than 100 and the records belong to the same category
我有一個客戶交易表,它有 3 列,id、Category、TranAmount。 現在我想找到 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
輸出應該是:
Id Category TranAmount
1 A 190
2 A 160
3 A 169
6 B 219
7 B 492
8 B 129
9 B 390
查看“差距和孤島”參考以更深入地了解該方法。 這是您可以閱讀的眾多內容之一: https : //www.red-gate.com/simple-talk/sql/t-sql-programming/the-sql-of-gaps-and-islands-in-sequences/
在此特定問題中,您有兩個條件會導致連續系列中斷,即類別更改或金額不符合閾值。
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;
我還不能真正對此進行測試,但請嘗試一下。
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)
如果 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)
請參閱演示。
結果:
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.