在SQL Server中,如何过滤联合结果?

时间:2017-04-18 07:40:00

标签: sql sql-server

我有一张桌子LiveProductStatus。根据特殊标准,我想过滤该表格的数据。

表结构是:

CREATE TABLE [dbo].[LiveCustomerStatus]
(
    [CustomerStatusID] [bigint] IDENTITY(1,1) NOT NULL,
    [CustomerID] [bigint] NOT NULL,
    [Status] [tinyint] NOT NULL,
    [StatusType] [tinyint] NOT NULL,
    [CreatedAt] [datetime] NOT NULL,
    [UpdatedAt] [datetime] NOT NULL
)

这是我的SQL查询:

select * 
from 
    (select * 
     from LiveProductStatus 
     where StatusType = 1 
       and (Status in (1, 2, 3, 4))

     union

     select * 
     from LiveProductStatus 
     where StatusType = 9 
       and (Status in (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13))

     union

     select * 
     from LiveProductStatus 
     where StatusType = 17 
       and (Status in (1, 2))) as temp 
where 
    temp.StatusType in (1, 9, 17) 
    and temp.Status in (1, 2, 4, 5)

过滤条件是:

StatusType      StatusValue
----------------------------------------------
1               1,2
9               1,2,3,4,5,6,7,8,9,10,11,12,13
17              1,2

现在假设我的StatusType为1,17,9,StatusValue

  • 2表示类型1
  • 2,3表示类型9
  • 1,2表示类型17

现在在上面的SQL查询中,我该如何应用此搜索?

2 个答案:

答案 0 :(得分:1)

with my_union as
(
  select * from LiveProductStatus where StatusType=1 and (Status in (1,2,3,4))
  union
  select * from LiveProductStatus where StatusType=9 and (Status in (1,2,3,4,5,6,7,8,9,10,11,12,13))
  union
  select * from LiveProductStatus where StatusType=17 and (Status in (1,2))
)

select *
from my_union    
where    (StatusType = 1 and Status =2)
      or (StatusType = 9 and  Status in (2,3))
      or (StatusType = 17 and  Status in (1,2))

CTE是一种非常优雅的方式来定义复杂的数据集,例如你的联合,并且可以轻松地对其进行后续过滤(或者将其与其他数据相结合,对其进行分组等等。)

PS:顺便说一句,这个非常简单的查询也会返回相同的结果。不需要工会:

select * 
from LiveProductStatus 
where    (StatusType = 1 and Status =2)
      or (StatusType = 9 and Status in (2,3))
      or (StatusType = 17 and Status in (1,2))

答案 1 :(得分:-1)

使用OR

select * 
from (
  select * 
  from LiveProductStatus 
  where (StatusType=1 and (Status in (1,2,3,4)))
  or (StatusType=9 and (Status in (1,2,3,4,5,6,7,8,9,10,11,12,13)))
  or (StatusType=17 and (Status in (1,2)))
) as temp 

where (temp.StatusType = 1 and temp.Status =2)
or (temp.StatusType = 9 and  temp.Status in (2,3))
or (temp.StatusType = 17 and  temp.Status in (1,2))

如果返回重复项,请添加DISTINCT

select DISTINCT *
from (...) as temp ...