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:
ncode
== 1 and code
== ABC
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)
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)