Search code examples
sqlcountgoogle-bigquerysubquerywindow-functions

SQL Select cases from a long table where ID is not duplicated


I have a table like below:

id | ncode | code
=================
1      1     ABC
1      2     DEF
2      1     ABC
3      1     ABC
4      1     ABC
4      2     DEF

I have two requirements:

  1. All records where ncode == 1 and code == ABC
  2. But only if id is not duplicated somewhere in the table (i.e., I don't want a record with code == ABC if that same id also has an ncode > 1 somewhere in the table.

select * from table where code == "ABC" and ncode == 1 will satisfy the first requirement but I can not figure out how to satisfy the second.

My desired output given the above example table would be:

id | ncode | code
=================
2      1     ABC
3      1     ABC

Per the answer below, I have utilized a window function:

select *
from (
   select *,
    sum(case when ncode > 1 then 1 else 0 end) over(partition by id) cnt
   from mytable
)
where code = 'ABC' and ncode = 1 and cnt = 0 order by id

I then implemented the Google BiqQuery specific syntax provided by the accepted answer:

select id, ANY_VALUE(ncode) ncode, ANY_VALUE(code) code
from mytable
group by id
having count(1) = 1
and (cpt, ncode) = ('ABC', 1)

Solution

  • Below should also work (BigQuery Standard SQL)

    #standardSQL
    SELECT id, 
      ANY_VALUE(ncode) ncode, 
      ANY_VALUE(code) code
    FROM `project.dataset.table`
    GROUP BY id
    HAVING COUNT(1) = 1
    AND (code, ncode) = ('ABC', 1)