1

我有以下查询:

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 连接。在不创建临时表的情况下,是否有其他解决方案可以做到这一点?任何帮助是极大的赞赏。

4

1 回答 1

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

但是,您确定要执行 aninsert而不是 anupdate吗?

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
于 2012-12-20T22:09:33.210 回答