SQL Server: How to use UNION with two queries that BOTH have a WHERE clause?

后端 未结 7 1488
礼貌的吻别
礼貌的吻别 2020-12-08 14:39

Given:

Two queries that require filtering:

select top 2 t1.ID, t1.ReceivedDate
  from Table t1
 where t1.Type = \'TYPE_1\'
 order by         


        
相关标签:
7条回答
  • 2020-12-08 15:30
    declare @T1 table(ID int, ReceivedDate datetime, [type] varchar(10))
    declare @T2 table(ID int, ReceivedDate datetime, [type] varchar(10))
    
    insert into @T1 values(1, '20010101', '1')
    insert into @T1 values(2, '20010102', '1')
    insert into @T1 values(3, '20010103', '1')
    
    insert into @T2 values(10, '20010101', '2')
    insert into @T2 values(20, '20010102', '2')
    insert into @T2 values(30, '20010103', '2')
    
    ;with cte1 as
    (
      select *,
        row_number() over(order by ReceivedDate desc) as rn
      from @T1
      where [type] = '1'
    ),
    cte2 as
    (
      select *,
        row_number() over(order by ReceivedDate desc) as rn
      from @T2
      where [type] = '2'
    )
    select *
    from cte1
    where rn <= 2
    union all
    select *
    from cte2
    where rn <= 2
    
    0 讨论(0)
提交回复
热议问题