使用任何OVER(PARTITION BY ...)?

时间:2018-05-16 22:14:16

标签: sql sql-server window-functions

例如,我有以下数据:

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

2 个答案:

答案 0 :(得分:2)

这有用吗?

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

答案 1 :(得分:1)

我会像这样使用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;