选择上次使用的名称

时间:2014-02-12 17:42:33

标签: sql sql-server sql-server-2008

我正在尝试从表中获取ID及其相应名称的列表。使用

select distinct cast([ctID] as int), [ctName]
  FROM [tbl_CTResults]

我发现名字随着时间的推移而发生了变化。我有一个额外的列([statdate]),可以让我知道哪个是最新名称。

我尝试使用像

这样的东西
SELECT cast([ctID] as int) ,max([statdate])

  FROM [InSightETL].[dbo].[tblPhWrk_WFM_iEX_CTResults] b
  group by cast([ctID] as int)

join 
SELECT * from (select distinct cast([ctID] as int)
      ,[ctName]
  FROM [InSightETL].[dbo].[tblPhWrk_WFM_iEX_CTResults] ) a
  on a.ctid=b.ctid

但除了语法错误之外,逻辑也是错误的。我知道我需要能够根据日期选择正确的记录,但我无法弄清楚如何将这两个信息联系在一起

3 个答案:

答案 0 :(得分:1)

您可以使用row_number()

执行此操作
select cdid, ctName
from (select cast([ctID] as int) as ctid, [ctName],
             row_number() over (partition by ctID order by startdate desc) as seqnum
      FROM [tbl_CTResults]
     ) t
where seqnum = 1;

答案 1 :(得分:1)

select *
from 
 (
   select cast([ctID] as int), [ctName],
      row_number() over (partition by ctID order by statdate desc) as rn
   FROM [tbl_CTResults]
 ) as dt
where rn = 1

答案 2 :(得分:1)

这是另一种使用CTE(公用表表达式)的方法:

;with cte (ctID, statdate)
as
(
    SELECT [ctID], max([statdate])
      FROM [InSightETL].[dbo].[tblPhWrk_WFM_iEX_CTResults]
      group by [ctID]
)
select cast(t.ctID as int), t.ctName
  from [InSightETL].[dbo].[tblPhWrk_WFM_iEX_CTResults] t
  join cte on cte.ctID = t.ctID and cte.statdate = t.statdate;

注意:此解决方案不会删除针对相同 ctID 的可能重复的 statdate