代码之家  ›  专栏  ›  技术社区  ›  Josh Laird

为行中的每个成功条件返回多行

  •  0
  • Josh Laird  · 技术社区  · 3 年前

    我试图为每一行输入返回一行或多行。这里有一个例子

    WITH data as (
      SELECT 1 id, ['main artist', 'supporting artist'] artists
      UNION ALL
      SELECT 2, ['main artist']
      UNION ALL
      SELECT 3, ['supporting artist']
      UNION ALL
      SELECT 4, []
    )
    SELECT
      id,
      CASE
        WHEN 'main artist' NOT IN UNNEST(artists) THEN "Include main artist"
        WHEN 'supporting artist' NOT IN UNNEST(artists) THEN "Include supporting artist"
        ELSE NULL
      END as error
    FROM data
    

    我想要的输出是

    身份证件 错误
    1. 无效的
    2. “包括支持艺术家”
    3. “包括主要艺术家”
    4. “包括主要艺术家”
    4. “包括支持艺术家”

    但是CASE语句只返回与第一个条件匹配的值(正如我所期望的 CASE 陈述

    我可能可以通过创建 UNION ALL 并以这种方式附加,但有更好的方法吗?

    0 回复  |  直到 3 年前
        1
  •  1
  •   Mikhail Berlyant    3 年前

    考虑以下方法

    select id, error from (
      select id, array(
        select 'Include ' || missing
        from unnest(['main artist', 'supporting artist']) missing
        left join t.artists artist
        on artist = missing
        where artist is null
      ) errors
      from `project.dataset.table` t
    ) left join unnest(errors) error
    # order by id          
    

    如果应用于问题中的示例数据,则输出为

    enter image description here