SQL 中 GROUP BY 和 STUFF 的替代方案

Alternative for GROUP BY and STUFF in SQL

我正在 AWS Athena 中编写一些 SQL 查询。我有 3 tables searchretrievalintent。在 search table 我有 2 列 id 和 term 即

id                 term
1                   abc
1                   bcd
2                   def
1                   ghd

我想要的是写一个查询得到:

id                  term
1               abc, bcd, ghd
2                    def

我知道这可以使用 STUFFFOR XML PATH 来完成,但是 Athena 还不支持 SQL 的所有功能。有没有其他方法可以实现这一目标。我当前的查询是:

select search.id , STUFF(
   (select ',' + search.term
    from search
    FOR XML PATH('')),1,1,'')
FROM search
group by search.id

另外,我还有一个问题。我有 retrieval table 由 3 列组成,即:

id         time        term
1           0          abc
1           20         bcd
1           100        gfh
2           40         hfg
2           60         lkf

我想要的是:

id          time       term
1           100        gfh
2            60        lkf

我想编写一个查询,根据 max 时间值获取 idterm。这是我当前的查询:

select retrieval.id, max(retrieval.time), retrieval.term
from search
group by retrieval.id, retrieval.term
order by max(retrieval.time)

我得到了重复的 ID 和术语。我认为这是因为,我在 id 和 term 上都做 group by。但是,我不确定如何在不使用 group by.

的情况下实现它

Group by 是一种分组操作:认为您正在对结果进行组合,并且必须找到最小值、最大值、计数等。 我只回答一个问题。 用它来找到问题 1 的答案 对于问题 2:

select 
from (select id, max(time) as time
      from search
      group by id, term
      order by max(time)
) search_1, search as search_2
where search_1.id = search_2.id
and search_1.time = search_2.time

XML 方法在 SQL 服务器中有问题。没有理由在任何其他数据库中尝试它。

一种方法使用数组:

select s.id, array_agg(s.term)
from search s
group by s.id;

因为数据库支持数组,所以你应该学会使用它们。您可以将数组转换为字符串:

select s.id, array_join(array_agg(s.term), ',') as terms
from search s
group by s.id;