2016-03-02 38 views
0

請諮詢更好的方法來做到這一點。 我相信這可以在一個查詢本身完成。tsql - 分組依據計算出的列

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

明顯的變化是使用子查詢:

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 
+0

感謝。不能投票。是新的。但感謝幫助。 –