【问题标题】:How to concatenate a conditional field and remove the same value如何连接条件字段并删除相同的值
【发布时间】:2022-01-16 23:56:31
【问题描述】:

我正在尝试使用 case 语句创建一个列,然后连接该列。这是一个示例代码。

WITH base AS (
SELECT ID, Date, Action, case when (Date is null then Action || '**' else Action End) Action_with_no_date
FROM <Table_Name>
)
SELECT ID, "array_join"("array_agg"(DISTINCT Action_with_no_date), ', ') Action_with_no_date
FROM base
GROUP BY ID;

基本上,Action_with_no_date 将显示Action 中的值的串联,并将'**' 字符串添加到每个Date 为空ID 的值中

在我这样做之后,我发现了一个边缘案例。

如果一个ID 使用相同的Action(即play),并且如果一个操作有date 而另一个没有,那么输出将有一个play 和一个play** 用于ID

但是,我希望它只显示一个带有 ** 的 play。 下面是ID = 1的示例数据

ID Date  Action
1  1/2/22 read
1  1/3/22 play
1  NULL   play

ID 的预期结果

ID Action_with_no_date
1  read, play**

我应该如何处理?

【问题讨论】:

  • 能否分享一些示例数据和预期结果?
  • 使用示例数据和预期结果进行了编辑。抱歉,我不确定如何在 Presto 中提供示例数据
  • 你好,云。 @KenWhite 的编辑是正确的 - 在标题的开头或结尾添加主题以形成自制的“标签”,我们将其删除。这就是标签系统的用途——请改用它。谢谢!
  • the preference to not add tags into titles 有一个规范参考(或为什么它们被删除)。

标签: sql concatenation presto athena


【解决方案1】:

你可以计算** 后缀,如果有任何行每个id 和操作都为null,则使用带有case 表达式的分析max()。然后将后缀与动作连接起来。

演示:

with mytable as (
SELECT * FROM (
    VALUES
        (1, '1/2/22', 'read'),
        (1, '1/3/22', 'play'),
        (1, NULL, 'play')
) AS t (id, date, action)
)

select id, array_join(array_agg(DISTINCT action||suffix), ', ')
from
(
select id, date, action,
       max(case when date is null then '**' else '' end) over(partition by id, action) as suffix
  from mytable
)s
group by id

结果:

1   play**, read

【讨论】:

  • 完美。非常感谢。
猜你喜欢
  • 1970-01-01
  • 2017-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多