[英]use ANY with OVER (PARTITION BY …)?
For example I have the following data: 例如,我有以下数据:
select *
into t1
from (
select 'apple' as company, 'Tom' as people
union select 'apple' as company, 'Jessi' as people
union select 'fb' as company, 'Alex' as people
union select 'fb' as company, 'Nick' as people
) as a
select * from t1
the data looks like: 数据如下:
company people
apple Jessi
apple Tom
fb Alex
fb Nick
I want to see if each company has Tom - at each row level. 我想看看每个公司的每一行都有汤姆吗?
Is there something similar to: 是否有类似的东西:
select *,
any(people = 'Tom') over (partition by company order by company) as find_tom
from t1
A work-around: 解决方法:
-- step 1: binary indicator has_tom
select *
,case when people = 'Tom' then 1 else 0 end
as has_tom
into t2
from t1
-- use max(has_tom) to see if tom exists for each partition
select *,
case when max(has_tom) over (partition by company order by company) = 1 then 'has tom' else 'no tom' end
as find_tom
from t2
this yields the result I want: 这产生了我想要的结果:
company people has_tom find_tom
apple Jessi 0 has tom
apple Tom 1 has tom
fb Alex 0 no tom
fb Nick 0 no tom
is this helpful? 这有帮助吗?
Select t1.*,
CASE WHEN
MAX(CASE WHEN people='Tom' THEN 1 ELSE 0 END)
OVER(Partition by company Order by (select null)) =1 THEN 'has Tom'
ELSE 'no Tom' END
FROM t1
SQl Fiddle: http://sqlfiddle.com/#!18/8ad91/19 SQl小提琴: http ://sqlfiddle.com/#!18/8ad91/19
I would just use case
like this: 我只想用
case
是这样的:
select t1.*,
(case when sum(case when people = 'tom' then 1 else 0 end) over (partition by company) > 0
then 'has tom' else 'no tom'
end) as find_tom
from t1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.