在雪花中使用“ DISTINCT ON”

时间:2020-02-13 11:24:21

标签: snowflake-cloud-data-platform

我有一个下面的查询,在这里我需要从联合结果中进行DISTINCT ON的allowed_id列,这在PostgreSQL中是可能的。我读过Snowflake使用类似的PostgreSQL,但是DISTINCT ON无效。

select distinct on (allowed_id), *  from (
  select listagg(distinct id) as allowed_id,   count (people) as totalpeople ,max(score) as maxscore , min(score) as minscore, 'n' as type from tableA
         where userid = 123  

  union
  select listagg(distinct id) as allowed_id,  count (people) as totalpeople, max(elscore) as maxscore , min(elscore) as minscore, 'o' as type from tableB
         where userid = 123 
   union
   select listagg(distinct id) as allowed_id, null, null , null , 'j' as type from tableC
         where userid = 123 
    union 
    select listagg(distinct id) as allowed_id, null, null , null , 'a' as type from tableD
         where userid = 123 
   )

1 个答案:

答案 0 :(得分:2)

雪花不支持“ DISTINCT ON”,但是您可以使用QUALIFY和ROW_NUMBER产生相同的结果:

SELECT * from (
select * from values (123,11,12,'a' ) as tableA (allowed_id, col2, col3, table_name)
union all
select * from values (123,21,22,'b' ) as tableA (allowed_id, col2, col3, table_name)
union all
select * from values (123,31,32,'c' ) as tableA (allowed_id, col2, col3, table_name)
union all
select * from values (123,41,42,'d' ) as tableA (allowed_id, col2, col3, table_name)
) 
where allowed_id = 123
QUALIFY ROW_NUMBER() OVER (PARTITION BY allowed_id ORDER BY allowed_id) = 1 ;

请检查:

https://docs.snowflake.net/manuals/sql-reference/constructs/qualify.html

https://docs.snowflake.net/manuals/sql-reference/functions/row_number.html