使用临时表连接查询

时间:2012-12-20 22:07:01

标签: sql sql-server join inner-join common-table-expression

我有以下查询:

select vkbr.vkID, vkbr.bid, vkbr.Date, vkbr.agID 
FROM camp c (NOLOCK)
JOIN    ag (NOLOCK) ON ag.campID = c.id
JOIN    vkbr WITH (NOLOCK) ON vkbr.agID = ag.id
where c.id = 648322
order by vkbr.vkID;

具有以下结果:

vkID        bid     Date                    agID
1072845175  NULL    2012-12-04 20:20:12.390 16074852
1072845177  0.74    2012-12-01 23:36:11.280 16074852
1072845177  0.18    2012-12-02 23:01:26.123 16074852
1072845177  0.72    2012-12-09 23:38:52.503 16074852
1072845177  0.62    2012-12-14 15:26:49.643 16074852
1072845178  2.91    2012-12-08 19:37:00.877 16074852
1072845178  0.73    2012-12-13 17:54:11.240 16074852
1072845178  2.70    2012-12-14 15:26:49.643 16074852

为了返回以下行,我使用cte然后使用SELECT:

1072845175  NULL    2012-12-04 20:20:12.390 16074852
1072845177  0.62    2012-12-14 15:26:49.643 16074852
1072845178  2.70    2012-12-14 15:26:49.643 16074852

with cte as
(    
select vkbr.vkID, vkbr.bid, vkbr.Date, vkbr.agID, ROW_NUMBER() OVER (PARTITION BY     vkbr.vkID ORDER BY vkbr.Date DESC) AS RowNumber
FROM camp c (NOLOCK)
JOIN ag (NOLOCK) ON ag.campID = c.id
JOIN vkbr WITH (NOLOCK) ON vkbr.agID = ag.id
where c.id = 648322
)

select vkID, bid, Date, agID
from cte
where RowNumber = 1

我需要从cte获得出价并将其插入到名为#t:

的现有临时表中
insert into #t (bid)    
select bid
from cte
where RowNumber = 1
and #t.Date = cte.Date
and #t.agId = cte.agId
and #t.vkId = cte.vkID;

我需要与#t进行这些连接,以确保我为正确的行插入正确的出价;但我收到这个错误:

“多部分标识符”#t.date“不受约束。”

我正在考虑创建另一个临时表,将cte中的行插入到临时表中,然后与#t连接。有没有其他解决方案来做这个没有创建临时表?非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

即使您要插入#t,它也不在select语句的范围内...尝试加入您插入的同一个表来执行此过滤:

insert into #t (bid)    
select cte.bid
from cte 
join #t 
  on #t.Date = cte.Date
  and #t.agId = cte.agId
  and #t.vkId = cte.vkID;
where cte.RowNumber = 1

但是,您确定要执行insert代替update吗?

update t
set t.bid = cte.bid
from cte 
join #t t 
  on t.Date = cte.Date
  and t.agId = cte.agId
  and t.vkId = cte.vkID;
where cte.RowNumber = 1
相关问题