我有一个查询,其中我为给定事件返回多行,例如:
ID | DateTime | String
1017436 | 2013-09-13 05:19:20.000 | Hello
1017436 | 2013-09-13 11:49:00.000 | World
我希望结果只包含任何给定 ID 的最早出现的行,但我遇到了麻烦。
我最初认为这样的查询将是答案:
; WITH cte AS
( SELECT *,
rn = ROW_NUMBER() OVER (PARTITION BY ixBug ORDER BY dt)
FROM dbo.BugEvent
)
SELECT ixBug, dt, s
FROM cte
WHERE
ixBug IN (SELECT Bug.ixBug
FROM
dbo.Bug
JOIN
dbo.Mailbox ON Mailbox.ixMailbox = Bug.ixMailbox
WHERE
ixBug = '1017436'
AND
YEAR(dtOpened) >= '2013'
AND
MONTH(dtOpened) = '09'
AND
sOriginalTitle NOT LIKE '\[web\]%' ESCAPE '\'
AND
dbo.Bug.ixProject = (SELECT ixProject
FROM dbo.Project
WHERE sProject = 'Support')
AND
dbo.Bug.ixCategory = (SELECT ixCategory
FROM dbo.Category
WHERE sCategory = '.inquiry')
AND
Bug.ixBug NOT IN(SELECT Bug.ixBug
FROM
dbo.Bug
JOIN
dbo.Mailbox ON Mailbox.ixMailbox = Bug.ixMailbox
WHERE
YEAR(dtOpened) >= '2013'
AND
MONTH(dtOpened) <= '09'
AND
sOriginalTitle LIKE '\[web\]%' ESCAPE '\'
AND
dbo.Bug.ixProject = (SELECT ixProject
FROM dbo.Project
WHERE sProject = 'Support')
AND
dbo.Bug.ixCategory = (SELECT ixCategory
FROM dbo.Category
WHERE sCategory = '.inquiry')))
AND
sVerb = 'Incoming Email';
但是,由于某种原因,结果保留了两行。