2016-07-15 73 views
0

不是最大的使用SQL,但我有写这个查询挣扎。情况是我有一个项目表。如果该项目是陈旧的“obso”并具有更换ID,然后在查询我应该选择,而不是已经过时的一个替换项目。这里是我有什么和一些照片,使其更清晰。SQL查询来寻找替代项目

select 
o.ReplacementItemID, 
o.ItemStatus, 
o.Description, 
o.ItemWarrantyID, 
o.Id as OriginalItemId 
from 
(
    select 
     id, 
     ItemStatus, 
     Description, 
     ItemWarrantyID, 
     ReplacementItemID 
    from item 
    where ItemStatus = 'obso' 
)o 
inner join Item i 
on o.ReplacementItemID = i.Id 

这给了我enter image description here

这是不正确的保修ID应该是110像下面的两个例子:

enter image description here

+0

听起来像是你应该选择'i.ItemWarrantyID'代替。 – sgeddes

+0

,因为对于项目ID 948032 ReplacementItemId为空。 –

+0

@JaydipJ这不是问题。原来的产品834852.更换为948032(您可以在ReplacementItemID请参阅834852)。您还可以在第一张图片中看到OriginalItemId。这个问题与Troy Bryant和sgeddes提到的ItemWarrantyID有关。 – CodyMR

回答

1

正如在评论中提到sgeddes你引用的错误ItemWarrantyID。你...

from 
(
select 
    id, 
    ItemStatus, 
    Description, 
    ItemWarrantyID, 
    ReplacementItemID 
from item 
where ItemStatus = 'obso' 
)o 

是所有关于原。之后的部分...

inner join Item i 
on o.ReplacementItemID = i.Id 

使它成为只有部分谁有替代品。问题在于,您只能使用原始文件,同时过滤掉所有没有替换的行。

所以你...

select 
o.ReplacementItemID, 
o.ItemStatus, 
o.Description, 
o.ItemWarrantyID, 
o.Id as OriginalItemId 

应该是...

select 
o.ReplacementItemID, 
o.ItemStatus, 
o.Description, 
i.ItemWarrantyID, 
o.Id as OriginalItemId 

假设你只是在寻找原稿(这好像你都基于该where ItemStatus = 'obso'和你inner join的和许多其他的东西)