1

我创建了一个包含 4 列的表,并根据大量 dataID 进行了排序:

      ID           Type             Item                Date
   AU761201      12.37.47         121212322     2012-07-12 22:21:12
   AU761201      12.37.42         157856388     2012-05-12 23:21:05
   AU761201      12.37.42         164687782     2009-02-12 12:37:24
   BD871015      15.31.62         651564488     2007-10-25 15:12:23
   DU551023      19.35.14         048040408     2011-11-05 14:15:23
   DU551023      19.35.14         056505654     2011-11-04 23:23:23
      .              .                .                   .
      .              .                .                   .
      .              .                .                   .
      .              .                .                   .
      .              .                .                   .

我要做的是检查是否有任何“ID”在 24 小时的时间空间内购买了两件相同的商品(相同的“类型”编号)(在给出的示例中为 DU 551023),并整理出适用的 ID。

我的大脑目前正在因处理这个问题而流血,我们深表感谢所有帮助。

谢谢!

4

3 回答 3

2

对于MySQL

SELECT T1.id
FROM TableName T1 INNER JOIN TableName T2 
   ON T1.id = T2.id AND T1.Type = T2.Type AND T1.Item > T2.Item
WHERE ABS(HOUR(TIMEDIFF(T1.date, T2.date))) <= 24

对于SQL 服务器

SELECT T1.id
FROM TableName T1 INNER JOIN TableName T2 
   ON T1.id = T2.id AND T1.Type = T2.Type AND T1.Item > T2.Item
WHERE ABS(DATEDIFF(hh, T1.date, T2.date)) <= 24
于 2012-09-03T19:59:50.707 回答
0

首先,您需要此表中的唯一键(用于区分记录)。假设它是 Item(否则在 T1.Item 中更改它!= T2.Item)。

select distinct T1.ID from Table T1, Table T2
where T1.ID = T2.ID and T1.Type = T2.Type 
  and Abs(T1.Date - T2.Date) < 1 and T1.Item != T2.Item
order by T1.ID
于 2012-09-03T19:57:24.560 回答
0

如果它的 SQL 服务器,那么你可以使用存在

SELECT DISTINCT
    a.ID
FROM    MyTable AS a
WHERE   EXISTS ( SELECT 1
             FROM   MyTable AS b
             WHERE  a.ID = b.ID
                    AND a.TYPE = b.Type
                    AND ABS(DATEDIFF(hour, a.Date, b.Date)) <= 24 )
ORDER BY a.ID 

或者你可以使用加入

SELECT DISTINCT a.ID
FROM MyTable AS a
INNER JOIN MyTable AS b
ON a.ID=b.ID AND a.TYPE=b.Type
WHERE ABS(DATEDIFF ( hour , a.Date , b.Date ))<=24
ORDER BY a.ID
于 2012-09-03T20:05:57.683 回答