我在SQL Server中有一个看起来像这样的查询。
SELECT
[ActionId], [CreationDate], [Description]
FROM
[Action]
INNER JOIN
People ON Action.personid = People.personid
WHERE
datediff(mm, Action.creationdate, getdate()) = 1
AND People.typeofpersonid = 8
但现在我想删除任何在一分钟内创建时间的响应。
因此,如果当前的回复是
ActionId CreationDate Description
---------------------------------------------------------
510467 2015-04-07 11:21:02.030 Registered errand.
510468 2015-04-07 11:21:25.840 Email sent to:....
510477 2015-04-07 11:50:22.830 Registered errand.
我希望第二行不会被退回。
有没有聪明的方法来做到这一点?
答案 0 :(得分:1)
你需要这样的东西:
SELECT [ActionId], [CreationDate], [Description]
FROM [Action]
inner join People on Action.personid = People.personid
where datediff(mm, Action.creationdate, getdate()) = 1
and People.typeofpersonid=8
AND NOT EXISTS
(
SELECT TOP 1 1
FROM [Action] Ain
inner join People Pin on Ain.personid = Pin.personid
where datediff(mm, Ain.creationdate, getdate()) = 1
and Pin.typeofpersonid=8
AND datediff(mi, Ain.creationdate, Action.creationdate)<1
AND Ain.ActionId <>Action.ActionId
)
一般的想法是你检查现有的行,如果有的话,那么你不要在查询中包含它。
答案 1 :(得分:1)
这应该有效:
SELECT
Action.ActionId,
Action.CreationDate,
Action.Description
FROM
Action
JOIN
(
SELECT
ActionId,
ROW_NUMBER() OVER (
PARTITION BY LEFT(CONVERT(VARCHAR, CreationDate, 120), 16)
ORDER BY CreationDate, ActionId
) AS row_num
FROM
Action
WHERE
DATEDIFF(mm, CreationDate, GETDATE()) = 1
) AS a2 ON (Action.ActionId = a2.ActionId AND a2.row_num = 1)
JOIN
People ON (Action.PersonDd = People.PersonId)
WHERE
DATEDIFF(mm, Action.CreationDate, GETDATE()) = 1
AND People.TypeOfPersonId = 8