Использование `DISTINCT ON` в Snowflake - PullRequest
0 голосов
/ 13 февраля 2020

У меня есть запрос ниже, где мне нужно сделать DISTINCT ON столбец allow_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 Ответ

2 голосов
/ 13 февраля 2020

Снежинка не поддерживает "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

...