如何将PostgreSQL的array_agg函数翻译成SQLite?

15

这个查询在PostgreSQL中可行:

  Select    ot.MCode,array_to_string(array_agg(tk1.TName || ',' || ot.TTime), ' - ') as oujyu_name_list
    From    TR_A ot
    inner join MS_B tk1 on ot.Code = tk1.Code
    Where   ot.Code in (Select Code From TR_C ) 
    Group byot.MCode

但在SQLite中无法使用,因为SQLite没有array_agg()函数。如何将此查询转换为SQLite?

2个回答

16

对于这个查询,你可以使用group_concat函数,它直接返回一个字符串:

SELECT ..., group_concat(tk1.TName || ',' || ot.TTime, ' - ')
FROM ...

1
值得一提的是,与ARRAY_AGG函数不同,您必须为GROUP_CONTACT指定GROUP_BY子句,更多信息请参见:https://dev59.com/AmEh5IYBdhLWcg3wpExF - younes0
@younes0 所有聚合函数在没有 GROUP BY 的情况下都返回单行结果;ARRAY_AGG 和 GROUP_CONCAT 没有区别。 - CL.
你是对的;我说的是关于特定情况下的Postgres,它允许省略group_by(如果你在查询一个表的情况下)。 - younes0
1
@younes0 所有 SQL 数据库都允许省略 GROUP BY(然后在使用任何聚合函数时使用一组来覆盖所有行)。 - CL.

8

SQLite现在拥有JSON1扩展(默认发行版已包含),可以对JSON对象进行分组和创建数组。例如,

select
  ot.MCode,
  json_group_array(json_object('tname', tk1.TName, 'ttime', ot.TTime)) as oujyu_name_list
from TR_A as ot
inner join MS_B as tk1
on (ot.Code = tk1.Code)
where ot.Code in (select code from TR_C)
group by ot.MCode;

第二列将会被格式化成JSON数组,例如 [{"tname":...,"ttime":...},...]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接