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

后端 未结 7 1518
礼貌的吻别
礼貌的吻别 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:17

    The answer is misleading because it attempts to fix a problem that is not a problem. You actually CAN have a WHERE CLAUSE in each segment of a UNION. You cannot have an ORDER BY except in the last segment. Therefore, this should work...

    select top 2 t1.ID, t1.ReceivedDate
    from Table t1
    where t1.Type = 'TYPE_1'
    -----remove this-- order by ReceivedDate desc
    union
    select top 2 t2.ID,  t2.ReceivedDate --- add second column
      from Table t2
     where t2.Type = 'TYPE_2'
    order by ReceivedDate desc
    

提交回复
热议问题