首页 > 解决方案 > 使用带有 SQL 联合的过滤器

问题描述

我有这个 SQL Server 查询。执行此查询将给出claimnumbers 和UW_Peril 的列表。

SQL 服务器:

select 
    ClaimNum, UW_Peril  
from 
    tableA

union

select  
    ClaimNum, UW_Peril 
from 
    (select 
         claimNum, 'Litigation' as UW_Peril 
     from 
         tableB
     where 
         Litigation = 1 and OrderofSuitReceived = 1) lt

我有2个案例:

  1. 如果每个索赔编号只有一行,则保持原样。
  2. 但是,如果每个索赔编号超过行,则选择 UW_Peril = 'Litigation' 所在的行

例子:

ClaimNum    UW_Peril
--------------------------
2053057     Litigation
2053057     Theft
2053125     Litigation
2052452     Subro

预期输出

例子:

ClaimNum    UW_Peril
--------------------------
2053057     Litigation
2053125     Litigation
2052452     Subro

我将如何修改它?提前致谢

标签: sql-serverunion

解决方案


您可以使用existsand :not existsunion all

select ClaimNum, UW_Peril
from tableB b
where exists (select 1 
              from tableB b1 
              where b1.ClaimNum = b.ClaimNum and b1.UW_Peril = b.UW_Peril)
union all
select ClaimNum, UW_Peril
from tableB b
where not exists (select 1 
                  from tableB b1 
                  where b1.ClaimNum = b.ClaimNum and b1.UW_Peril = b.UW_Peril) and
      b.UW_Peril = 'Lititgation';

推荐阅读