Sql哪里有记录具有相同的字段值但时间戳不同

时间:2018-01-30 13:06:46

标签: sql sql-server select exists

我正在弄清楚如何在我的where子句中写入有相同字段值但时间戳不同的记录。

表格看起来像这样

ID       NotificationID        DateTime
1        55555                 2018-01-29 23:00:36.983
2        55555                 2018-01-25 18:38:09.513
3        55555                 2018-01-25 18:38:09.513
4        55555                 2018-01-25 18:38:09.513

如果有ID = 1的记录与#2, #3, #4具有相同的 NotificationID ,但它的日期时间不同,则为真

如果表格只有#2, #3, and # 4具有相同的 NotificationID 和DateTime,则为

我怎样才能在where子句中写一些内容告诉我这个ID#1这样的记录是真的。

感谢您的帮助

2 个答案:

答案 0 :(得分:0)

但是,找不到所需的输出,以查找第二行具有相同NotificationIDtimestamp不同的行EXISTS

select ID, NotificationID, timestamp
from your_table t1
where exists(
  select 1
  from your_table t2
  where t1.NotificationID = t2.NotificationID and
        t1.timestamp != t2.timestamp
)

答案 1 :(得分:0)

请尝试此操作 - 我已经为您生成了两个解决方案。

CREATE TABLE notify
(
     ID       INT
    ,NotificationID INT
    ,[DateTime] DATETIME
)
GO

INSERT INTO notify VALUES
(1,55555,'2018-01-29 23:00:36.983'),
(2,55555,'2018-01-25 18:38:09.513'),
(3,55555,'2018-01-25 18:38:09.513'),
(4,55555,'2018-01-25 18:38:09.513')

INSERT INTO notify VALUES 
(6,11111,GETDATE()),
(7,11111,GETDATE())

输出1

SELECT Id,NotificationID,[DateTime],CASE WHEN a <> b THEN 'False' else 'True' End co FROM 
(
    SELECT * , COUNT(*) OVER (PARTITION BY NotificationID) a , COUNT(*) OVER (PARTITION BY NotificationID,[DateTime]) b
    FROM notify
)k

Id          NotificationID DateTime                co
----------- -------------- ----------------------- -----
6           11111          2018-01-30 18:44:18.170 True
7           11111          2018-01-30 18:44:18.170 True
2           55555          2018-01-25 18:38:09.513 False
3           55555          2018-01-25 18:38:09.513 False
4           55555          2018-01-25 18:38:09.513 False
1           55555          2018-01-29 23:00:36.983 False

(6 rows affected)

输出2

SELECT NotificationID,MAX(CASE WHEN a <> b THEN 'False' else 'True' End) co 
FROM 
(
    SELECT * , COUNT(*) OVER (PARTITION BY NotificationID) a , COUNT(*) OVER (PARTITION BY NotificationID,[DateTime]) b
    FROM notify
)k GROUP BY NotificationID



NotificationID co
-------------- -----
11111          True
55555          False

(2 rows affected)
相关问题