1

我有一个存储过程,它返回一个指定 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
4

2 回答 2

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
于 2013-08-02T21:30:13.360 回答
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
于 2013-08-02T21:24:24.893 回答