I have a table like the following:
ID | col1 | col2 | col3 | col4 |
---|---|---|---|---|
A | 100 | 400 | 30 | 800 |
B | 600 | 50 | 500 | 75 |
and I want a query where I can return something like
ID | col1 | col2 | col3 | col4 |
---|---|---|---|---|
A | 0 | 1 | 0 | 1 |
B | 1 | 0 | 1 | 0 |
Except, I want the logic to look at each row, and for each row find which two columns have the top 2 values. I imagine there may be a few CTEs or subqueries involved. Even getting to a CTE that would produce the following outcome would be good enough, but don't know how to get to this CTE:
ID | top_2_col_name |
---|---|
A | col2 |
A | col4 |
B | col1 |
B | col3 |
Is there a way to do aggregate and window functions row-wise instead of column wise? I'm using Google's BigQuery SQL.