2

我有一个具有以下结构的表

ID  Person  LOG_TIME
-----------------------------------
1   1       2012-05-21 13:03:11.550
2   1       2012-05-22 13:09:37.050 <--- this is duplicate
3   1       2012-05-28 13:09:37.183
4   2       2012-05-20 15:09:37.230
5   2       2012-05-22 13:03:11.990 <--- this is duplicate
6   2       2012-05-24 04:04:13.222 <--- this is duplicate
7   2       2012-05-29 11:09:37.240

我有一些用数据填充这个表的应用程序工作。

有一条业务规则,每个人每 7 天只能有 1 条记录。

从上面的例子中,记录# 2,5 和 6 被认为是重复的,而 1,3,4 和 7 是可以的。

我想要一个 SQL 查询来检查在不到 7 天内是否有同一个人的记录。

4

4 回答 4

1

请在此处查看我对 SQLFiddle 的尝试。

您可以使用连接DATEDIFF()来查找相隔不到 7 天的记录:

WITH TooClose
AS
(
    SELECT
        a.ID AS BeforeID,
        b.ID AS AfterID
    FROM
        Log a
        INNER JOIN Log b ON a.Person = b.Person
                        AND a.LOG_TIME < b.LOG_TIME
                        AND DATEDIFF(DAY, a.LOG_TIME, b.LOG_TIME) < 7
)

但是,这将包括您不认为“重复”的记录(例如,ID 3,因为它太接近 ID 2)。根据您所说,我推断如果记录太接近的记录本身就是“重复”,则该记录不是“重复”。

因此,要应用此规则并获取重复项的最终列表:

SELECT
    AfterID AS ID
FROM
    TooClose
WHERE
    BeforeID NOT IN (SELECT AfterID FROM TooClose)
于 2012-12-08T17:18:56.720 回答
1
;WITH cte AS
 (
  SELECT ID, Person, LOG_TIME,
         DATEDIFF(d, MIN(LOG_TIME) OVER (PARTITION BY Person), LOG_TIME) AS diff_date
  FROM dbo.Log_time
  )
SELECT *
FROM cte
WHERE diff_date BETWEEN 1 AND 6

SQLFiddle上的演示

于 2012-12-09T22:05:48.667 回答
0

请看一下这个样本。

参考:SQLFIDDLE

询问:

select person, 
datediff(max(log_time),min(log_time)) as diff,
count(log_time)
 from pers 
 group by person
;

select y.person, y.ct
from (
select person, 
datediff(max(log_time),min(log_time)) as diff,
count(log_time) as ct
 from pers 
 group by person) as y
where y.ct > 1
and y.diff <= 7
;


PERSON  DIFF    COUNT(LOG_TIME)
1   1   3
2   8   3


PERSON  CT
1   3
于 2012-12-08T15:22:09.747 回答
0

声明@Count int

set @count=(
select COUNT(*) 
from timeslot  
where (( (TimeFrom<@Timefrom and TimeTo >@Timefrom) 
      or (TimeFrom<@Timeto and TimeTo >@Timeto))
      or (TimeFrom=@Timefrom or TimeTo=@Timeto)))
于 2019-04-12T05:53:30.387 回答