繁体   English   中英

在OVER(PARTITION BY…)中使用ANY?

[英]use ANY with OVER (PARTITION BY …)?

例如,我有以下数据:

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

数据如下:

company     people
apple       Jessi
apple       Tom
fb          Alex
fb          Nick

我想看看每个公司的每一行都有汤姆吗?

是否有类似的东西:

   select *,
        any(people = 'Tom') over (partition by company order by company) as find_tom
    from t1

解决方法:

-- 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

这产生了我想要的结果:

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

这有帮助吗?

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小提琴: http ://sqlfiddle.com/#!18/8ad91/19

我只想用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM