如果存在,如何选择符合条件的行,否则随机选择另一个?

How to choose row that met criteria if exist other wise randomly choose another?

我有以下 table:

article_id , locale, category_name, is_primary_local
  1             en              answers          True
  1             es              respuestas       False
  2             en              questions        False
  2             de              fragen           False
  2             it              domande          False

关键是(article_id, locale)

我想创建一个 table 以 article_id 作为键。 逻辑是,如果有主要本地,则将其用于 category_name 如果没有,则随机选择一个。每个 article_id.

只能有一个 primary_local

所以输出看起来像:

article_id , category_name
   1            answers
   2             fragen    -- or domande, questions

这是我试过的:

SELECT 
      article_id,
      MIN(CASE WHEN is_primary_local  Then category_name else ?????  END) as category_name
From table
GROUP BY article_id

但是我不知道如何完成这个案例条件?

我正在使用 presto sql。

考虑以下查询:

select article_id, locale, category_name, is_primary_local
from (
    select 
        t.*,
        row_number() 
            over(partition by article_id order by is_primary_local desc, random()) rn
    from mytable t
) t
where rn = 1

内部查询对 article_id 组内的记录进行排名,按 is_primary_local 降序排列(这将 true 值放在首位),然后随机排列。外部查询筛选每组的顶部记录。作为使用 window 函数的奖励,您可以 return 所有列(不仅是 article_idcategory_name)。

Demo on DB Fiddle:

第一次执行:

article_id | locale | category_name | is_primary_local 
---------: | :----- | :------------ | :--------------- 
         1 | en     | answers       | t                
         2 | en     | questions     | f                

第二次执行:

article_id | locale | category_name | is_primary_local | rn
---------: | :----- | :------------ | :--------------- | -:
         1 | en     | answers       | t                |  1
         2 | de     | fragen        | f                |  1

如果您不介意 随机选择一个 到 return 最小值 category_name 那么在您的代码中使用 COALESCE() 之类的这个:

SELECT 
      article_id,
      COALESCE(
        MIN(CASE WHEN is_primary_local  THEN category_name END),
        MIN(category_name) 
      ) as category_name
From tablename
GROUP BY article_id