请建议更好的方法来做到这一点。 我确信这可以在一个查询中完成。
declare @tempTale table (ID bigint, ArticleDate datetime,CommentDate
datetime,MostRecentDate datetime)
declare @MinDate datetime;
set @MinDate = getdate();
set @MinDate = DATEADD(YEAR,-100,@MinDate)
insert into @tempTale
select USER_ARTICLEID, User_Article.CREATED_ON, coalesce(comment.CREATED_ON,@MinDate),
case when coalesce(User_Article.CREATED_ON,@MinDate) > coalesce(comment.CREATED_ON,@MinDate) then User_Article.CREATED_ON else comment.CREATED_ON end as MostRecentDate
from User_Article left join Comment on Comment.CONTENTID = User_Article.USER_ARTICLEID and comment.CONTENT_TYPE = User_Article.CONTENT_TYPE
order by MostRecentDate desc
select distinct top 10 ID,MAX(MostRecentDate) from @tempTale group by ID
order by MAX(MostRecentDate) desc
答案 0 :(得分:0)
明显的变化是使用子查询:
select distinct top 10 ID, MAX(MostRecentDate) from
(
select
USER_ARTICLEID as ID,
(case
when coalesce(User_Article.CREATED_ON,@MinDate) > coalesce(comment.CREATED_ON,@MinDate) then User_Article.CREATED_ON
else comment.CREATED_ON end) as MostRecentDate
from User_Article
left join Comment
on Comment.CONTENTID = User_Article.USER_ARTICLEID and comment.CONTENT_TYPE = User_Article.CONTENT_TYPE
)
group by ID
order by 2 desc
但您没有对计算列进行分组,因此您可以使用简单的列:
select distinct top 10
USER_ARTICLEID as ID,
(case
when coalesce(User_Article.CREATED_ON,@MinDate) > coalesce(comment.CREATED_ON,@MinDate) then User_Article.CREATED_ON
else comment.CREATED_ON end) as MostRecentDate
from User_Article
left join Comment
on Comment.CONTENTID = User_Article.USER_ARTICLEID and comment.CONTENT_TYPE = User_Article.CONTENT_TYPE
group by USER_ARTICLEID
order by 2 desc