如果在另一个表中不存在数据,如何从表中进行选择

时间:2015-04-24 14:42:01

标签: sql sql-server sql-scripts

这应该很简单。我不知道为什么我感到难过。

我有两张相似的牌桌。让我们说它们每个只有2列:PartNumber和Order。

在单个语句中,我想从WorkItemPartsFiltered中选择PartNumbers,其中Order = ABC,但如果不存在,我想从WorkItemParts中选择它们,其中Order = ABC

--WorkItemParts
PartNumber | Order
123        | ABC
456        | ABC
789        | ABC
012        | ABC
123        | DEF
456        | DEF
389        | GHI


--WorkItemPartsFiltered
PartNumber | Order
123        | ABC
456        | ABC
789        | ABC
456        | DEF
389        | GHI

5 个答案:

答案 0 :(得分:2)

SELECT [Order]
      , COALESCE( WorkItemParts.PartNumber
                      ,WorkItemPartsFiltered.PartNumber) AS PartNumber
FROM WorkItemParts
LEFT JOIN WorkItemPartsFiltered 
ON WorkItemPartsFiltered.[Order] = WorkItemParts.[Order]

答案 1 :(得分:2)

您可以使用合并,并结合左连接:

select
coalesce (WIPF.PartNumber, WIP.PartNumber)
from
WorkItemParts WIP
left join WOrkItemPartsFiltered WIPF
  on wip.order = wipf.order

答案 2 :(得分:1)

您必须使用带有JOIN的case语句,如下所示:

SELECT Order, CASE WHEN WorkItemParts.PartNumber is null 
  THEN WorkItemPartsFiltered.PartNumber
  ELSE WorkItemParts.PartNumber END
FROM WorkItemParts
LEFT JOIN WorkItemPartsFiltered 
         ON (WorkItemPartsFiltered.Order = WorkItemParts.Order)

答案 3 :(得分:1)

您也可以写为:

if not exists (
select *
from WorkItemPartsFiltered 
where [Order] = 'KLM')
begin
    select PartNumber,[Order] 
    from WorkItemParts
    where [Order] = 'KLM'
end 
else
begin
    select PartNumber,[Order] 
    from WorkItemPartsFiltered
    where [Order] = 'KLM'    
end

DEMO

答案 4 :(得分:1)

另一种方法:

Create Table dbo.partsfiltered
(
PartNumber int,
OrderNum varchar(5),
SourceTable varchar(20)

);
Insert into partsfiltered
Values (123,'abc','filtered'), (678,'ghi','filtered');

Create Table dbo.parts
(
PartNumber int,
OrderNum varchar(5),
SourceTable varchar(20)
);
Insert into parts 
Values (123,'abc','full'), (345,'def','full'), (678,'ghi','full');


with cte as 
(
        Select  PartNumber,
                OrderNum,
                SourceTable,
                ROW_NUMBER() Over (Partition By PartNumber order by SourceTable) as [SourceTableRank]
        From
        (
        select * From partsfiltered
        union 
        select * From parts
        )a

)
Select PartNumber, OrderNum, SourceTable
From cte
where SourceTableRank = 1;

SQLFiddle here