Skip to content
Advertisement

Invalid group by expression error when using any_value with max and window function in Snowflake

I was given a query and I am attempting to modify it in order to get the most recent version of each COMP_ID. The original query:

I then attempted to use a window function to grab only the highest version for each comp_id. This is the modified query:

When attempting to compile the below error is given:

SQL compilation error: [COMP_DATA.COMP_ID] is not a valid group by expression

I had originally thought the issue was the ANY_VALUE on COMP_VERSION, but after removing the ANY_VALUE the same error was given. The only way I found to not get an error was removing the 4 MAX fields and all of the ANY_VALUE()’s, as shown below:

Of course this is not at all sufficient since I need the 4 max fields.

I have also tried creating the table with the max fields and from that new table using the window function to select the highest COMP_VERSION of each COMP_ID, but the same error was given.

Advertisement

Answer

When you added your QUALIFY clause you dropped the GROUP BY clause from your SQL, aggregate function like MAX, need all selections to be aggregate function OR to have a GROUP BY clause.

So if you only want the best row per the grouping clause, which you note, you aggregate functions need to be explicitly windowed. Thus

There is a small chance you will need to add a set of brackets around those MAX’s like

But I suspect it will work out of the box. And I assumed you don’t want the row_number so pushed it into the qualify (because it will always be the value 1)

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement