我的数据:
ColumnA Column B ColumnC
A Hi Yes
A Hello NULL
B Hola Yes
B Hola Yes
B Hi NULL
C ABCD Yes
我的SQL应该可以执行以下操作:
预期结果是:
ColumnA Column B ColumnC
A Hi Yes
A Hello NULL
B Hola Yes
B Hola Yes
B Hi NULL
如何选择满足上述规则的所有值?
答案 0 :(得分:2)
一种方法使用GROUP BY
和HAVING
:
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 :(得分: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 :(得分:1)
我认为过滤实际上可以通过'WHERE'子句而不是'HAVING'来更好地处理。
真正的原始请求“只选择那些包含Yes和Null的A组在结果中”但是不需要聚合来限制行。我不知道使用SUM函数是否需要额外的费用,但为什么还需要额外的工作。
我不知道这是不是比较远,但为什么你会去商店,拿起一堆苹果,当你到达登记册时,开始拉出一些不好的东西?< / p>
试试这个:
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
只会显示为一个组合在一起,但在你的示例输出中,你有两次...
答案 3 :(得分: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
答案 4 :(得分:1)
尝试这个没有分组和cluase,
strtotime
答案 5 :(得分: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;