2017-06-04 44 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;