2013-08-02 33 views
1

去除Select语句行我有一个存储过程返回缺少某种特定的ID项目表。例如:exec getMissingItems '1'将返回缺少的ID = 1如项目的列表:'A', 'B', 'C'。现在我的跟踪,当接收到这些项目,因此它们被存储到数据库中'A Received' & B received等等。我希望能够只显示尚未收到的物品,例如,如果我现在请exec getMissingItems '1',它只会返回'C'SQL:在插入

所有的信息被存储到数据库表

TABLE1 
ID | Event 
1 | A Missing 
1 | B Missing 
1 | C Missing 
1 | A Received 
1 | B Received 

所以目前getMissingItems是简单地调用:

SELECT Event FROM TABLE1 WHERE Event LIKE '%Missing'

它返回的项目缺少一个表,但仍然返回他们,即使他们缺少

RETURNED TABLE 
    Event 
A Missing 
B Missing 
C Missing 
+0

您可以编辑您的问题,并添加一些架构信息?甚至可能在[sqlfiddle](http://sqlfiddle.com/)上提出一个概念验证? –

+0

在描述模式设计时,您需要更具体。乍一看,看起来简单的加入就足够了。 –

+0

是它返回一个表或者是“A”,“B”,“C”的一个字符串 – logixologist

回答

3

这应该为你工作。您需要根据ID和事件解析的标识符离开连接。然后找到事件中具有“缺失”的不匹配行。

下面是一个SQL小提琴链接到这个例子 - http://sqlfiddle.com/#!3/2d668/1/0

create table #table1 
(
    ID int, 
    [Event] varchar(100) 
); 

go 

insert into #table1 values (1, 'A Missing'); 
insert into #table1 values (1, 'B Missing'); 
insert into #table1 values (1, 'C Missing'); 
insert into #table1 values (1, 'A Received'); 
insert into #table1 values (1, 'B Received'); 

go 

with cte as 
(
    select id, [Event], substring([Event], 1, patindex('% %', [Event]) -1) as ItemId 
    from #table1 
) 

select a.Event 
from cte a 
    left join cte b on 
     a.id = b.id and     -- IDs must match 
     a.ItemId = b.ItemId and   -- the ItemId from the parsed Event must match on the left side 
     a.Event like '%Missing' and  -- items that match have a 'Missing' on the "left" 
     b.Event like '%Received'  -- items that match have a 'Received' on the "right" 
where b.ID is null      -- rows that did not match on the right 
and a.Event like '%Missing'    -- row has missing in the event on the left side 


drop table #table1; 

go 
+0

谢谢!你是一个拯救生命的人。为了一个看似微不足道的任务,这么多工作。 – AToya

0

编辑答案

看看这对你的作品好一点......

CREATE TABLE #temp (id, event, missing, recieved) 
INSERT INTO #temp 
SELECT Id, Event, case when event like '%missing%' then 1 else 0 END 
CASE WHEN event like '%recieved%' then 1 else 0 
FROM TABLE1 

SELECT Event from Table1 t join #temp tt on t.id = tt.id 
WHERE missing =1 and recieved = 0 
+0

这仍然会返回A B和C,而不是实际包含“已收到”的事件。如果有一个事件'A Received',我不希望它显示'A Missing'。 – AToya