Skip to content
Advertisement

Setting rules for max() with strings

Each record in my table has a random selection of these strings, so it looks like

I want to get the highest value of “fruit” for each record, except I want it to be sorted lower if it contains the string guava. This is the output that I’d like and I’m using Snowflake SQL

output:

Currently, I’m trying to do this by assigning every possible value of fruit a number with a case when statemnet, using max on that list and the converting the result back into a string. That won’t work in my case because the names of the fruit will change, so I don’t want a hard coded list

this is what I’ve tried

Advertisement

Answer

Desired results with Snowflake (as tagged):

  • array_agg() can be ordered
  • for the order we can sort first by guava existing, and then by fruit.
  • [0] obtains the first element of array_agg().

enter image description here

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