tim*_*guy 6 sql oracle conditional count
我试过搜索其他帖子,但只能找到关于一个固定值的重复.
想象一下下表:
????????????????????
? customer ? color ?
????????????????????
? 1 ? black ?
? 1 ? black ?
? 2 ? red ?
? 2 ? black ?
? 3 ? red ?
? 3 ? red ?
? 3 ? red ?
? 4 ? black ?
? 5 ? black ?
? 5 ? green ?
? 6 ? purple?
????????????????????
Run Code Online (Sandbox Code Playgroud)
我想选择"重复"意味着以下客户:
目前我可以选择的只是关于黑色复制品,但我不能将它与"一个黑色,不再是红色"的条件结合起来.
SELECT customer FROM events WHERE
color = 'black'
group by customer
having count(*) > 1
Run Code Online (Sandbox Code Playgroud)
也许我可以先计算黑人,然后再加入现有的桌子计算额外的黑人和红人?
我希望得到以下结果作为客户:1,2.更好的是一个输出,我知道客户是双黑色还是黑色+一些红色:
???????????????????????????????????????
? customer ? blackOnly ? blackPlusRed ?
???????????????????????????????????????
? 1 ? yes ? no ?
? 2 ? no ? yes ?
???????????????????????????????????????
Run Code Online (Sandbox Code Playgroud)
您希望所有客户都有“黑色”且至少有两条记录。您可以通过条件聚合来做到这一点:
select
customer,
case when count(distinct color) = 1 then 'yes' else 'no' end as blackOnly,
case when count(distinct color) > 1 then 'yes' else 'no' end as blackPlusRed
from events
group by customer
having count(*) > 1
and count(case when color = 'black' then 1 end) > 0;
Run Code Online (Sandbox Code Playgroud)
更新:如果允许其他颜色,查询会略有变化:
select
customer,
case when count(case when color = 'red' then 1 end) = 0 then 'yes' else 'no' end as blackOnly,
case when count(case when color = 'red' then 1 end) > 0 then 'yes' else 'no' end as blackPlusRed
from events
group by customer
having count(case when color = 'black' then 1 end) > 1
or
(
count(case when color = 'black' then 1 end) > 0
and
count(case when color = 'red' then 1 end) > 0
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1005 次 |
| 最近记录: |