#TAble是模棱两可的

时间:2014-05-08 23:48:43

标签: sql-server-2008 temp-tables self-join

我收到的错误表明#Plans含糊不清。这种情况发生在我自己加入一张桌子时,我不知道为什么。以下是导致错误的代码:

Alter Table #Plans
Add SecondPlanDate date

Update #Plans
Set 
    SecondPlanDate = Min (P2.PlanPurchaseDate) Over (Partition By P1.PatientID, P1.PlanPurchaseDate)
From
#Plans as P1
Inner Join
#Plans as P2
on
P1.PatientID = P2.PatientID
Where
P2.PlanPurchaseDate > P1.PlanPurchaseDate
;

Select
*
From
#Plans  

任何建议都将不胜感激。

谢谢,

4 个答案:

答案 0 :(得分:3)

我认为您需要使用表别名:

UPDATE P1
SET P1.SecondPlanDate ...

答案 1 :(得分:1)

将查询修改为

Update P1
Set 
    P1.SecondPlanDate = Min (P2.PlanPurchaseDate) Over (Partition By P1.PatientID, P1.PlanPurchaseDate)
From
#Plans as P1

答案 2 :(得分:0)

试试这个:

UPDATE #Plans
SET SecondPlanDate = P2.FirstPlanPurchaseDate
FROM #Plans P1
INNER JOIN ( SELECT PatientID,
                    MIN(PlanPurchaseDate) AS FirstPlanPurchaseDate
             FROM #Plans
             GROUP BY PatientID) P2
ON P1.PatientID = P2.PatientID

答案 3 :(得分:0)

Update #Plans
Set 
SecondPlanDate = <your value>
From
#Plans , #Plans  P2
Where
#Plans.PatientID = P2.PatientID
and P2.PlanPurchaseDate > #Plans.PlanPurchaseDate
//ie the solution is to reference the update table in the join as well
相关问题