我在使用 sqlite 查詢時遇到了一些問題:
select t.* from transactions t
join (
select description, amount, created_at, count(*) from transactions
where account_id = 1
group by description, amount having count(*) > 1
) t2
ON t.description = t2.description
and t.amount = t2.amount
and strftime('%s', t2.created_at) - strftime('%s', t.created_at) between -60 and 60
;
基本上,我有一個包含 3 個重要列的表,如果滿足 3 個條件,我想獲得重復的行:
- 相同的描述。
- 相同數量。
- 重復的行必須在 60 秒內創建。
它部分作業,如果時間差在 -60 和 60 之間,那么它會正確顯示 2 個重復的行,超出該范圍的任何內容都只顯示不應該發生的行。
樣本資料:
insert into transactions (description, amount, created_at) values ('Internet', 19.99, '2021-11-29 11:30:00');
insert into transactions (description, amount, created_at) values ('Internet', 12.99, '2021-11-29 11:31:00');
使用這些值執行查詢時,不應顯示任何內容。因為即使日期在 1 分鐘內,金額也是不同的。
insert into transactions (description, amount, created_at) values ('Internet', 12.99, '2021-11-29 11:33:00');
insert into transactions (description, amount, created_at) values ('Internet', 12.99, '2021-11-29 11:35:00');
使用這些值執行查詢時,不應顯示任何內容。因為日期不在 1 分鐘內。
insert into transactions (description, amount, created_at) values ('Internet', 19.99, '2021-11-29 11:30:00');
insert into transactions (description, amount, created_at) values ('Internet', 19.99, '2021-11-29 11:31:00');
使用這些值執行查詢時,它必須顯示兩行。
uj5u.com熱心網友回復:
你可以這樣做EXISTS:
SELECT t1.*
FROM transactions t1
WHERE EXISTS (
SELECT 1
FROM transactions t2
WHERE t2.rowid <> t1.rowid
AND t2.description = t1.description
AND t2.amount = t1.amount
AND ABS(strftime('%s', t2.created_at) - strftime('%s', t1.created_at)) <= 60
);
請參閱演示。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/370837.html
上一篇:每組優化的最大n
