使用带有SQL联合的过滤器

时间:2018-06-13 14:48:18

标签: sql-server union

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

SQL Server:

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 ='诉讼'
  3. 示例:

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

    预期输出

    示例:

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

    我该如何修改?提前致谢

1 个答案:

答案 0 :(得分:0)

您可以将existsnot 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';