【问题标题】:How to find duplicate records in MySQL, but with a degree of variance?如何在 MySQL 中查找重复记录,但有一定程度的差异?
【发布时间】:2021-01-11 00:45:36
【问题描述】:

假设我有以下表结构和数据:

+------------------+-------------------------+--------+
| 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 天。

因为“汉堡王”的交易是在三天内(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 |
+------------------+-------------------------+--------+

我走了吗?或者这甚至可能吗?提前致谢。

【问题讨论】:

  • Burger King 何时超过 3 个日期?像日期 23,22,21,20,19,18,17 哪个需要?或where date = 使用?所以日期 20 -3 日期和 +3 日期总计 7
  • 如果Burger King 23,22,21,20,19,18,17 16 15 14 哪个取??

标签: mysql sql count duplicates window-functions


【解决方案1】:

你可以使用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

【讨论】:

  • 哦,这太不可思议了!这正是我想要的。非常感谢。
猜你喜欢
  • 1970-01-01
  • 2010-10-25
  • 1970-01-01
  • 2020-07-06
  • 2014-03-18
  • 2012-08-04
  • 2013-11-26
相关资源
最近更新 更多