简体   繁体   中英

SQL/BigQuery: case when statement over partition by

I have a table about conversations. There are many conversation elements for unique conversation IDs

conv_id element_id author_type part_type
1 11 bot comment
1 12 bot comment
2 22 bot comment
2 23 bot comment
2 24 admin note
3 32 bot note

and I want to write a case when statement for each conversation id, -> if author_type is 'bot' and part_type is 'comment', then label it as 'bot' in a new column for all the rows of that conversation id.

So the result will look like this:

conv_id element_id author_type part_type tag
1 11 bot comment bot
1 12 bot comment bot
2 22 bot comment bot
2 23 bot comment bot
2 24 admin note bot
3 32 bot note

for example, the when conv_id is 2, it wrote 'bot' even if one of the rows didn't meet the criteria.

I tried this code, but it is not working, and the error message is 'over keyword must follow a function call'.

CASE
when
author_type = 'bot' and part_type = 'comment'
then 'bot'
over (partition by conversation_id)
end as tag

Thank you

I edited the post and changed one condition.

Consider below query.

if author_type is 'bot' and part_type is 'comment', then label it as 'bot' in a new column for all the rows of that conversation id.

SELECT *,
       MAX(IF(author_type = 'bot' AND part_type = 'comment', 'bot', NULL)) OVER (PARTITION BY conv_id) AS tag
  FROM sample_table
 ORDER BY conv_id

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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