简体   繁体   English

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

[英]In SQL Server, how to filter union result?

I have a table LiveProductStatus .我有一张表LiveProductStatus Based on special criteria I want to filter my that table's data.根据特殊标准,我想过滤该表的数据。

Table structure is:表结构为:

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
)

This is my SQL query:这是我的 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)

Filter criteria is:过滤条件是:

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

Now suppose my StatusType is 1, 17, 9, and StatusValue are现在假设我的StatusTypeStatusValue ,而StatusValue

  • 2 for type 1 2 类型 1
  • 2,3 for type 9 2,3 类型 9
  • 1,2 for type 17 1,2 类型 17

Now in my above SQL query, how can I apply this search?现在在我上面的 SQL 查询中,如何应用此搜索?

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))

CTEs are a very elegant way to define a complex data set, like your union, and posteriorly filter it easily (or join it with additional data, group it, etc. ...). CTE 是一种非常优雅的方式来定义一个复杂的数据集,比如你的联合,并轻松地对其进行后部过滤(或者将它与其他数据结合起来,对其进行分组等......)。

Use OR使用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))

If this returns duplicates, add in DISTINCT :如果这返回重复项,请添加DISTINCT

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM