如何基于SQL Server中的表从结果中排除记录

时间:2018-09-20 14:11:16

标签: sql sql-server

我有一个结果集,该结果集来自以下sp:

SELECT g2.ID, g2.[Name]
    FROM cte c
        LEFT JOIN #Market gc WITH(NOLOCK) ON c.ID = gc.ID
        INNER JOIN list.Type gt WITH(NOLOCK) ON g2.TypeId = gt.TypeID
    WHERE  
        gt.MarketCount IS NOT NULL
    GROUP BY g2.GameID, g2.[Name] 
ORDER BY g2.[Name]

这是输出

 ID     | Name
    2   |Apple
    5   |Pear
    14  |Strawberry

现在我有另一个称为映射的表,如下所示

ID  | Name
14  | Strawberry

我要实现的是,从存储过程返回的上述数据结果中,我想将其与映射表进行比较,如果它们在映射中的ID与结果集匹配,则应忽略该行并给我以下结果,例如:预期结果

        ID  | Name
        2   |Apple
        5   |Pear

由于映射表中存在ID 14,因此该记录应已删除

3 个答案:

答案 0 :(得分:0)

使用左联接并按未映射表的位置进行过滤

with t1 as
     (SELECT g2.ID, g2.[Name]
            FROM cte c
                LEFT JOIN #Market gc WITH(NOLOCK) ON c.ID = gc.ID
                INNER JOIN list.Type gt WITH(NOLOCK) ON g2.TypeId = gt.TypeID
            WHERE  
                gt.MarketCount IS NOT NULL
            GROUP BY g2.GameID, g2.[Name] 
        ORDER BY g2.[Name
    ) select t1.* from t1 left join mappingt t2 on t1.id=t2.id
      where t2.id is null

答案 1 :(得分:0)

您的查询是完全错误的,我在您的查询中没有找到任何g2别名,所以我会这样做:

WITH t AS (
     SELECT DISTINCT g2.ID, g2.[Name]
     FROM cte c INNER JOIN 
          #Market gc WITH(NOLOCK) 
          ON c.ID = gc.ID INNER JOIN 
          list.Type gt WITH(NOLOCK) 
          ON g2.TypeId = gt.TypeID
    WHERE gt.MarketCount IS NOT NULL
)

SELECT t.*
FROM t 
WHERE NOT EXISTS (SELECT 1 FROM mappingt M WHERE m.id = t.id);

在使用NOLOCK提示之前,我建议先访问Aaron blog

答案 2 :(得分:0)

由于您提到了存储过程,因此可以将该存储过程的结果映射到表中。然后使用标准的左联接过滤结果

declare @temptable table (id int, name varchar(255))
insert into @temptable exec storedProcname 

select * 
    from @temptable t
    left join Mapping m on m.Id = t.Id
    where m.id is null