SQL Server 2008中没有临时表的SQL查询

时间:2012-08-17 07:05:13

标签: sql sql-server-2008

我有2个表,我需要输出临时表

WorkItem

ItemID  ItemName Status
1      xyz       3
2      abc       3
3      MNO       2

WorkItemTrack

TrackID  ItemID  Status
1       1        1
2       1        2
3       1        3
4       2        1
5       2        2
6       3        1
7       3        2

这是我的查询

select ItemName, WorkItem.Status from WorkItem Inner join WorkItemTrack ON WorkItem.ItemID=WorkItemTrack.ItemID
where WorkItemTrack.Status=2

&安培;这是我的输出

  ItemName Status
  XYZ       3
  ABC       3
  MNO       2

但我只需要输出状态为2的MNO

 ItemName Status 
  MNO       2

如何不使用临时表

4 个答案:

答案 0 :(得分:1)

这同样有效

Select x.ItemName,x.Status
From (Select * from WorkItem where Status = 2) x
Join (Select ItemID from WorkItemTrack where Status = 2) y
on x.ItemID=y.ItemID

答案 1 :(得分:0)

select i.ItemName, i.Status
from WorkItem i
inner join WorkItemTrack t ON i.ItemID = t.ItemID
where t.Status = 2
AND i.Status = 2

答案 2 :(得分:0)

你可以做

select ItemName, WorkItem.Status from WorkItem 
Inner join WorkItemTrack ON WorkItem.ItemID=WorkItemTrack.ItemID 
where WorkItemTrack.Status=2 and WorkItem.Status=2

select * from 
  (select ItemName, WorkItem.Status as status from WorkItem 
   Inner join WorkItemTrack ON WorkItem.ItemID=WorkItemTrack.ItemID 
    where WorkItemTrack.Status=2) 
where status=2

(如果你以后需要更复杂,并希望用初始结果做其他事情)

答案 3 :(得分:0)

你的问题含糊不清,但这可能是你想要的:

SELECT ItemName, wi.Status
FROM WorkItem AS wi
JOIN WorkItemTrack AS wit ON (wi.ItemID=wit.ItemID) AND (wi.Status=wit.Status)
WHERE wit.Status=2

或者

SELECT ItemName, wi.Status
FROM WorkItem AS wi
JOIN WorkItemTrack AS wit ON (wi.ItemID=wit.ItemID) AND (wit.Status=2)
WHERE wi.Status=2