从具有最大和最小时间戳的行中有效地进行选择

时间:2015-11-23 12:59:28

标签: tsql

对于每个项目,我们都有许多任务。我需要在每个项目的第一个和最后一个任务上找到tasktype。我尝试了以下方法来获取第一个任务类型,并计划在最后一个类似的方面做一些事情:

SELECT projects.ProjectNumber,
    COALESCE(
        (SELECT Tasktype 
         FROM [Facts].[ProjectTable] pt 
         WHERE 
             pt.ProjectNumber=projects.ProjectNumber 
             AND pt.Timestamp = 
                 (SELECT MIN(x.Timestamp) 
                 FROM [Facts].[ProjectTable] x 
                 where 
                     x.ProjectNumber = projects.ProjectNumber
                 )
         ),-1) AS [First Tasktype]
FROM [Facts].[ProjectTable] projects
GROUP BY projects.ProjectNumber

但性能非常慢(我确定2个嵌套子查询没有帮助)。如何有效地获得每个项目的第一个和最后一个任务类型?

1 个答案:

答案 0 :(得分:1)

select * 
from 
( 
select ProductNumber, TaskType
     , row_number() over (partition by ProductNumber order by Timestamp asc)  ttasc  
     , row_number() over (partition by ProductNumber order by Timestamp desc) ttdesc 
  FROM [Facts].[ProjectTable]
) tt   
where tt.ttasc = 1 or tt.ttdesc = 1

或一行

with cte as
( 
select ProductNumber, TaskType
     , row_number() over (partition by ProductNumber order by Timestamp asc)  ttasc  
     , row_number() over (partition by ProductNumber order by Timestamp desc) ttdesc 
  FROM [Facts].[ProjectTable]
)
select * 
from cte as cte1 
join cte as cte2 
      on cte1.ProductNumber = cte2.ProductNumber 
     and cte1.ttasc  = 1 
     and cte2.ttdesc = 1