【问题标题】:How to translate the PostgreSQL array_agg function to SQLite?如何将 PostgreSQL array_agg 函数转换为 SQLite?
【发布时间】:2014-11-14 03:04:40
【问题描述】:

此查询在 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?

【问题讨论】:

    标签: postgresql sqlite android-sqlite aggregate-functions


    【解决方案1】:

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

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

    【讨论】:

    • 值得一提的是,与 ARRAY_AGG 函数不同,必须为 GROUP_CONTACT 指定 GROUP_BY 子句,更多信息:stackoverflow.com/questions/22190200/…
    • @younes0 All 聚合函数返回没有 GROUP BY 的单行; ARRAY_AGG 和 GROUP_CONCAT 之间没有区别。
    • 你是对的;我说的是允许省略 group_by 的特定案例 postgres(如果你在一个表中查询,我猜)
    • @younes0 所有 SQL 数据库允许省略 GROUP BY(然后在使用任何聚合函数时对所有行使用一个组)。
    【解决方案2】:

    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":...},...].

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-02
      • 1970-01-01
      • 2018-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-07
      • 2015-09-12
      相关资源
      最近更新 更多