计算在其他对象修改日期之后创建的对象

时间:2014-08-01 17:09:49

标签: sql tsql

我试图计算在t-SQL查询中特定日期之后创建的所有帖子:

select a.ParentID as [Post Link]
     , count(DISTINCT a.id) as [Answers after edition]
     , q.LastEditDate as [Last Edition]
     , a.creationdate as [Answered On]
     , DATEDIFF(hour, q.LastEditDate, a.creationdate) as [Hours after edition]
from posts a 
inner join posts q on q.id = a.ParentID
where q.posttypeid = 1 -- Q
and a.posttypeid = 2 -- A
and q.LastEditorUserId = ##userid##
and a.creationdate > q.LastEditDate
and q.AnswerCount > 1
group by a.ParentID

结果是:

Column 'posts.LastEditDate' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

此查询是对另一个的修改:

select q.id as [Post Link]
     , q.owneruserid as [User Linkl]
     , q.LastEditDate as [Last Edition]
     , a.creationdate as [Answered On]
     , DATEDIFF(hour, q.LastEditDate, a.creationdate) as [Hours after edition]
from posts q 
inner join posts a on a.id = q.AcceptedAnswerId
where q.posttypeid = 1 -- Q
and a.posttypeid = 2 -- A
and q.LastEditorUserId = ##userid##
and a.creationdate > q.LastEditDate
order by [Hours after edition]

更改包括后者仅比较AcceptedAnswerId所在的帖子。我想做同样的事情,但这次将具有相同q.Id的那些分组。

这几乎是我想要的:

select a.id as [Answer Link]
     , q.owneruserid as [User Linkl]
     , q.LastEditDate as [Last Edition]
     , a.creationdate as [Answered On]
     , DATEDIFF(hour, q.LastEditDate, a.creationdate) as [Hours after edition]
from posts a 
inner join posts q on q.id = a.ParentID
where q.posttypeid = 1 -- Q
and a.posttypeid = 2 -- A
and q.LastEditorUserId = ##userid##
and a.creationdate > q.LastEditDate
and q.AnswerCount > 1

但不按ParentId分组。

这就是我的期望:

Post Link   | Answer Count | Hours after edition
http://link |            3 |                   3

我不太热衷于保持"编辑后的时间"但如果它保持更好。

1 个答案:

答案 0 :(得分:1)

将评论转化为答案。在你的第一个代码中:

 , q.LastEditDate as [Last Edition]
 , a.creationdate as [Answered On]

您收到的错误是因为它们不在group by语句中,并且脚本不知道如何处理多个值。如果您将它们包含在组中,则可能会为每个父ID获取多行...我认为您希望将最大日期作为最后一次编辑并将最小日期作为第一次创建。

顺便说一句......我认为你必须在这里使用MSSQL。如果您使用的是MySQL,它将在没有分组的情况下执行您的查询,只是随机填充这两个字段。唉Mysql。

列上的过滤器在哪里,具有聚合上的过滤器。由于我们将它们移动到max(date)或min(date),它们变成聚合并且需要在having子句而不是where子句中。从具有您需要的订单

中选择分组

最终剧本(由Braiam提供):

select a.ParentId as [Post Link]
 , count(DISTINCT a.id) as [Answers after edition]
 --, q.LastEditDate as [Last Edition]
 --, a.creationdate as [Answered On]
 --, DATEDIFF(hour, q.LastEditDate, a.creationdate) as [Hours after edition]
from posts a 
inner join posts q on q.id = a.ParentID
where q.posttypeid = 1 -- Q
and a.posttypeid = 2 -- A
and q.LastEditorUserId = ##userid##
and q.AnswerCount > 1
group by a.ParentId
having max(q.LastEditDate) < min(a.creationdate)