Home > database >  How to select rows corresponding to a randomly selected column value in SQL
How to select rows corresponding to a randomly selected column value in SQL

Time:11-02

My query returns a result like shown in the table. I would like to randomly pick an ID from the ID column and get all the rows having that ID. How can I do that in SnowFlake or SQL:

ID Postalcode Value ...
1e3d NK25F4 3214 ...
1e3d NK25F4 3258 ...
1e3d NK25F4 3354 ...
1f74 NG2LK8 5524
1f74 NG2LK8 5548
3e9a N6B7H4 3694
3e9a N6B7H4 3325
38e4 N6C7H2 3654 ...

CodePudding user response:

There is a Snowflake function to return a fix number of "random" rows enter image description here

WITH DATA AS (
select '1e3d' id,'NK25F4' postalcode,3214 some_value union all   
select '1e3d' id,'NK25F4' postalcode,3258 some_value union all 
select '1e3d' id,'NK25F4' postalcode,3354 some_value union all   
select '1f74' id,'NG2LK8' postalcode,5524 some_value union all  
select '1f74' id,'NG2LK8' postalcode,5548 some_value union all  
select '3e9a' id,'N6B7H4' postalcode,3694 some_value union all  
select '3e9a' id,'N6B7H4' postalcode,3325 some_value union all  
select '38e4' id,'N6C7H2' postalcode,3654 some_value )
SELECT * FROM DATA ,LATERAL (SELECT ID FROM DATA SAMPLE(2 ROWS)) I WHERE I.ID = DATA.ID  
  • Related