我写的异常页面使用MySQL追赶重复计费追赶项以下情形。
项目细节,其中有以下两列(其中包括)表输入。
ItemCode VARCHAR(50), BillEntryDate DATE
它经常发生,同一项目的议案被输入多次,但过了一段几天。喜欢,
"Football","2019-01-02"
"Basketball","2019-01-02"
...
...
"Football","2019-01-05"
"Rugby","2019-01-05"
...
"Handball","2019-01-05"
"Rugby","2019-01-07"
"Rugby","2019-01-10"
在上面的例子中,该项目足球结算了两次 - 第一次在2Jan并再次5Jan。同样,项英式橄榄球被标榜上5,7,10Jan三次。
我期待编写简单SQL其可以拾取的每个项目[比方说,使用不同(ItemCode)子句],然后显示所有其是在为期30天的重复记录。在上述情况下,期望输出应该是以下5个记录:
"Football","2019-01-02"
"Football","2019-01-05"
"Rugby","2019-01-05"
"Rugby","2019-01-07"
"Rugby","2019-01-10"
我试图运行下面的SQL:
select * from tablen a, tablen b, where a.ItemCode=b.ItemCode and a.BillEntryDate = b.BillEntryDate+30;
然而,这似乎是运行长而不显示任何记录是非常低效的。有没有得到一个不太复杂且快速的方法的可能性?
我没有研究现有的主题(如How do I find duplicates across multiple columns?),但它正在迎头赶上重复,其中两列具有相同的值。我的要求是一列相同的值,第二列在不同的长达一个月的日期范围。
您可以使用:
select t.*
from tablen t
where exists (select 1
from tablen t2
where t2.ItemCode = t.ItemCode and
t2.BillEntryDate <> t.BillEntryDate and
t2.BillEntryDate >= t1.BillEntryDate - interval 30 day and t2.BillEntryDate <= t1.BillEntryDate + interval 30 day
);
这将拿起在对中的两个副本。
出于性能考虑,你想对(ItemCode, BillEntryDate)
的索引。
随着EXISTS
:
select ItemCode, BillEntryDate
from tablename t
where exists (
select 1 from tablename
where
ItemCode = t.ItemCode
and
abs(datediff(BillEntryDate, t.BillEntryDate)) between 1 and 30
)