【问题标题】:SQL: Removing rows from Select Statement on InsertSQL:在插入时从 Select 语句中删除行
【发布时间】:2013-08-04 06:31:35
【问题描述】:

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

【问题讨论】:

  • 您可以编辑您的问题并添加一些架构信息吗?甚至可以在sqlfiddle 上进行概念验证?
  • 在描述架构设计时需要更加具体。乍一看,似乎一个简单的连接就足够了。
  • 它是作为一个表返回还是一个字符串'A','B','C'
  • 对不起,我编辑了代码,希望现在已经足够清楚了。
  • 您将两个信息放在一列中。这打破了第一范式。值 'A missing' 应该是单独列中的两个值,例如 Item=A 和 EventType=missing。

标签: sql sql-server sql-server-2008 tsql select


【解决方案1】:

这应该适合你。您需要根据事件的 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

【讨论】:

  • 谢谢!你是一个救生员。一项看似微不足道的任务需要做这么多工作。
【解决方案2】:

修改后的答案

看看这对你有没有更好的效果......

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

【讨论】:

  • 这仍然返回 A B 和 C,而不是实际包含 'Received' 的事件。如果有“A Received”事件,我也不希望它显示“A Missing”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-16
  • 1970-01-01
  • 2022-12-18
  • 1970-01-01
  • 2022-06-11
  • 1970-01-01
相关资源
最近更新 更多