2017-06-04 41 views
1

我的数据:SQL服务器:集团通过基于一列,并获得基于其他列列

ColumnA     Column B   ColumnC   
A       Hi     Yes 
A       Hello    NULL 
B       Hola    Yes 
B       Hola    Yes 
B       Hi     NULL 
C       ABCD    Yes 

我的SQL应该能够做到以下几点:

  1. 集团通过A柱
  2. 仅选择那些包含是和无两种结果的A的组合

预期结果为:

ColumnA     Column B   ColumnC   
A       Hi     Yes 
A       Hello    NULL 
B       Hola    Yes 
B       Hola    Yes 
B       Hi     NULL 

如何选择满足上述规则的所有值?

+0

请将您的预期结果发布为文字,并发布您的查询尝试 – TheGameiswar

+0

为什么您好的结果出现在您的结果中 – TheGameiswar

回答

1
select * from t 
    where 
columnA in 
    (select columnA from T where columnC is NULL) and 
columnA in 
    (select columnA from T where columnC = 'Yes') 
2

一种方法是使用GROUP BYHAVING

select columnA 
from t 
group by columnA 
having sum(case when columnC is null then 1 else 0 end) > 0 and 
     sum(case when columnC = 'yes' then 1 else 0 end) > 0; 
1

我觉得过滤实际上由“WHERE子句,而不是“具有”可以更好地处理。
确实原始请求声明“只选择那些在结果中包含”是“和”否“的A组,但不需要聚合来限制行。我不知道是否有使用SUM函数的额外成本,但为什么要做额外的工作。
我不知道这是否是一个相当大的比较,但你为什么要去商店,拿起一堆苹果,当你到达注册表,开始拉出一些坏的?

试试这个:

SELECT ColumnA, ColumnB, ColumnC 
FROM myTable 
WHERE ColumnC IS NULL || ColumnC = 'yes' 
--GROUP BY ColumnA, ColumnB, ColumnC --commented per additional comment below. 

还要说明。请仔细检查您的示例数据,如果您正在分组,我不能告诉你所做的只是将'c'作为columnA的值排除在外。另外,我将认为两行:

ColumnA     Column B   ColumnC 
B       Hola    Yes 

本来只显示为一体,因为它们会被组合到一起,但在你品尝你拥有了它有两次输出...

1
create table #t(ColumnA varchar(10),ColumnB varchar(10),ColumnC varchar(10)) 
insert into #t 
    select 'A','Hi','Yes' union all 
    select 'A','Hello',NULL union all 
    select 'B','Hola','Yes' union all 
    select 'B','Hola','Yes' union all 
    select 'B','Hi',NULL union all 
    select 'C','ABCD','Yes' 
select * from ( 
    select *,sum(case when ColumnC='YES' THEN 1 else 0 end)over(partition by ColumnA) as YesCount 
      ,sum(case when ColumnC is null then 1 else 0 end)over(partition by ColumnA) as NULLCount 
    from #t 
) as t where t.YesCount>0 and t.NULLCount>0 
 
    ColumnA ColumnB ColumnC YesCount NULLCount 
1 A Hi Yes 1 1 
2 A Hello NULL 1 1 
3 B Hola Yes 2 1 
4 B Hola Yes 2 1 
5 B Hi NULL 2 1 
1

尝试此无需由组和具有cluase,

create table #t(ColumnA varchar(10),ColumnB varchar(10),ColumnC varchar(10)) 
insert into #t 
    select 'A','Hi','Yes' union all 
    select 'A','Hello',NULL union all 
    select 'B','Hola','Yes' union all 
    select 'B','Hola','Yes' union all 
    select 'B','Hi',NULL union all 
    select 'C','ABCD','Yes' 

    ;With CTE as 
    (
    select * 
    ,ROW_NUMBER()over(partition by ColumnA order by ColumnA)rn 
    from #t 
    where ColumnC is null or ColumnC='Yes' 
    ) 
    select * from cte c 
    where exists(select columnA from cte c1 
    where c.ColumnA=c1.ColumnA and rn>1) 

    drop table #t 
1
select t1.* 
from t t1 
inner join 
    (select sum(case when t3.colc is null then 1 when t3.colc = 'Yes' then 1 else 0 end) as cnt, 
    t3.cola 
    from t t3 
    group by cola) t2 on t1.cola = t2.cola 
    where t2.cnt >= 2;