次のテーブル構造とデータがあるとします。
+------------------+-------------------------+--------+
| transaction_date | transaction_description | amount |
+------------------+-------------------------+--------+
| 2020-08-20 | Burger King | 10.06 |
| 2020-08-23 | Burger King | 10.06 |
| 2020-08-29 | McDonalds | 6.48 |
| 2020-09-04 | Wendy's | 7.45 |
| 2020-09-05 | Dairy Queen | 14.36 |
| 2020-09-06 | Wendy's | 7.45 |
| 2020-09-13 | Burger King | 10.06 |
+------------------+-------------------------+--------+
説明と金額が一致する重複したトランザクションを見つけたいのですが、日付には多少の変動があります+/- 3日間。
「バーガーキング」のトランザクションは互いに3日以内(2020-08-20および2020-08-23)であるため、重複としてカウントされますが、2020-09-13のエントリはカウントされません。
これまでに次のクエリがありますが、分散の度合いの部分が私を困らせています。
SELECT t.transaction_date, t.transaction_description, t.amount
FROM transactions t
JOIN (SELECT transaction_date, transaction_description, amount, COUNT(*)
FROM transactions
GROUP BY transaction_description, amount
HAVING count(*) > 1 ) b
ON t.transaction_description = b.transaction_description
AND t.amount = b.amount
ORDER BY t.amount ASC;
理想的には、出力が次のようなものになるようにしたいです。
+------------------+-------------------------+--------+
| transaction_date | transaction_description | amount |
+------------------+-------------------------+--------+
| 2020-08-20 | Burger King | 10.06 |
| 2020-08-23 | Burger King | 10.06 |
| 2020-09-04 | Wendy's | 7.45 |
| 2020-09-06 | Wendy's | 7.45 |
+------------------+-------------------------+--------+
私は道を外れていますか?それともこれは可能ですか?前もって感謝します。
使用できますexists
:
select t.*
from mytable t
where exists (
select 1
from mytable t1
where
t1.transaction_description = t.transaction_description
and t1.transaction_date <> t.transaction_date
and t1.transaction_date >= t. transaction_date - interval 3 day
and t1.transaction_date <= t. transaction_date + interval 3 day
MySQL 8.0を実行している場合、ウィンドウの日付範囲内のカウントが妥当な代替手段です。
select t.*
from (
select t.*,
count(*) over(
partition by transaction_description
order by transaction_date
range between interval 3 day preceding and interval 3 day following
) cnt
from mytable t
) t
where cnt > 1
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加