Snowflake Vs MS-SQL - Part 34 - NTH_VALUE

      


NTH_VALUE

If you have a dataset and you want to calculate the third highest value in each group as below:

+---------+---------+
| COLUMN1 | COLUMN2 |
|---------+---------+
|       1 |      10 |
|       1 |      11 |
|       1 |      12 |
|       1 |      20 |
|       1 |      21 |
|       1 |      22 |
|       2 |      30 |
|       2 |      31 |
|       2 |      32 |
|       2 |      40 |
|       2 |      41 |
|       2 |      42 |
+---------+---------+


Expected Result:
+---------+---------+
| COLUMN1 | COLUMN2 |
|---------+---------+
|       1 |      12 |
|       2 |      32 |
+---------+---------+



MS-SQL Server 

You can not achieve this by using the TOP Clause as below: 



In Snowflakewe can go with a similar approach, however, we can use the inbuilt function NTH_VALUE.



For more details, you can refer to the following NTH_VALUE


Similarly, we have FIRST_VALUE to get the first value and LAST_VALUE to get 

last value of the data set.

Yogesh Shinde

LinkedInProfile

<<< Back Next >>> 

Comments

Popular posts from this blog

Snowflake Vs MS-SQL - Part 36 - SPLIT_TO_TABLE

Snowflake Vs MS-SQL - Part 63 - ON Clause & Cross Join

Snowflake Vs MS-SQL - Part 33 - INITCAP