Sql 按键变量分组从长表中选择案例

Sql 按键变量分组从长表中选择案例,sql,google-bigquery,Sql,Google Bigquery,我有一张如下表: caseid | ncode | code | test 1 1 ABC TRUE 1 2 DEF TRUE 2 1 ABC TRUE 3 1 DEF TRUE 3 2 HIJ FALSE 其中,caseid表示单个案例。此表创建了一种关系,即每个案例可以有多个与其关联的代码(ncode和code)测试只是

我有一张如下表:

caseid | ncode | code | test
   1       1      ABC    TRUE
   1       2      DEF    TRUE
   2       1      ABC    TRUE 
   3       1      DEF    TRUE
   3       2      HIJ    FALSE
其中,
caseid
表示单个案例。此表创建了一种关系,即每个案例可以有多个与其关联的代码(
ncode
code
)<代码>测试只是一个跟踪感兴趣的布尔值的变量

我对我的查询有具体要求:

  • 我需要
    code=ABC
    ncode=1
    test=TRUE
    的所有情况此标准具有最高优先级
  • 在#1中的这些情况中,我需要创建一个名为
    hasdef
    的附加列,该列是一个布尔值,用于指示特定的
    caseid
    是否有任何其他行,其中
    code=DEF
    test=TRUE
    。如果是,则应为
    TRUE
    ,否则为
    FALSE
  • 因此,从上表中,应该返回的是:

    caseid | ncode | code | test | hasdef
       1       1      ABC    TRUE   TRUE
       2       1      ABC    TRUE   FALSE
    
    caseid=1
    返回,因为
    code=ABC
    ncode=1
    test=TRUE
    <因为在第二行中,
    caseid=1
    code=DEF
    test=TRUE

    caseid=2
    返回,因为
    code=ABC
    ncode=1
    test=TRUE
    hasdef=FALSE
    因为没有其他行具有
    caseid=2
    其中
    code=DEF

    caseid=3
    不返回。即使有一行
    code=DEF
    test=TRUE
    ,第一个标准(
    code=ABC
    ncode=1
    )也不是首先满足的

    到目前为止,我已经做到了这一点,但我不相信它能按预期工作:

    select tab1.*, tab2.code is not null as hasdef from
    (select * from mytable
    where code = 'ABC' and ncode = 1) as tab1
    
    left join (
    select caseid, any_value(code) code,  any_value(test) test
    from mytable
    group by caseid
    having code = 'DEF' and test is true
    ) as tab2
    using(caseid)
    
    order by caseid
    

    下面是BigQuery标准SQL

    #standardSQL
    select * from (
      select *, 
        0 < countif(code = 'DEF' and test is true) over(partition by caseid) as hasdef
      from `project.dataset.table` 
    )
    where code = 'ABC' and ncode = 1 and test is true    
    
    select * from (
      select *, 
        0 < countif(code = 'DEF' and test) over(partition by caseid) as hasdef
      from `project.dataset.table` 
    )
    where code = 'ABC' and ncode = 1 and test