使用带有CTE和排名功能的插入时出错

时间:2015-06-30 10:07:29

标签: sql-server common-table-expression ranking

我有一个包含员工信息的表temp.Results。此表包含HR使用的信息。员工记录的所有更改都在table.i.e。

select * from temp.Results where ID=1
1,'2 main st','salem','2009-01-01','2000-01-01'
1,'34 elm st','acton','2013-03-09','2000-01-01'

Datevalidated是我们输入最新信息的时间.DateProcessed是我们第一次输入员工信息。

 WITH ordered as( 
select ID, name, address,city, DateValidated, DateProcessed
,ROW_NUMBER() over (partition by DateValidated
       order by DateValidated desc) as rn from 
  aa.temp.Results (nolock) where id=31  
  ) 
  insert into tempResults2(ID, name, address,city, DateValidated, DateProcessed)
select ID, name, address,city, DateValidated, DateProcessed from ordered where rn = 1 ;

我尝试使用上面的查询将每个员工的最新信息转换为teable,但是会收到此错误。

Invalid object name 'tempResults2'

如何解决这个问题?

由于 MR

3 个答案:

答案 0 :(得分:1)

您可以将where子句与select * into一起使用。

WITH ordered as
( 
    select 
        ID, name, address,city, DateValidated, DateProcessed,
        ROW_NUMBER() over (partition by DateValidated order by DateValidated desc) as rn 
    from aa.temp.Results  where id=31  
  ) 

select * into tempResults2 from ordered where rn = 1 ;

答案 1 :(得分:1)

WITH ordered as( 
select ID, name, address,city, DateValidated, DateProcessed
,ROW_NUMBER() over (partition by DateValidated
       order by DateValidated desc) as rn from 
  aa.temp.Results (nolock) where id=31  
  ) 
  select ID, name, address,city, DateValidated, DateProcessed 
  into tempResults2 
  from ordered 
  where rn = 1 ;

答案 2 :(得分:0)

您查询错误。当你可以像这样使用nolock

WITH ordered as( 
select ID, name, address,city, DateValidated, DateProcessed
,ROW_NUMBER() over (partition by DateValidated
       order by DateValidated desc) as rn from 
  aa.temp.Results with(nolock) where id=31  
  )