我有一个存储过程,它返回指定ID缺少的项目表。例如:exec getMissingItems '1'
将返回ID = 1
缺少的项目列表,例如:'A', 'B', 'C'
。现在我正在跟踪收到这些项目的时间,以便将它们存储到数据库中'A Received'
& B received
等等。我希望只能显示尚未收到的项目,例如,如果我现在拨打exec getMissingItems '1'
,它只会返回'C'
。
所有信息都存储在数据库表中
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 :(得分:3)
这对你有用。您需要根据事件中的ID和已解析的标识符离开连接。然后找到在事件中具有“Missing”的不匹配行。
以下是此示例的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
答案 1 :(得分: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