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
I would just use case
like this:
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.