17

This query works in 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

but it does not work in SQLite, because SQLite does not have the array_agg() function. How can this query be converted to SQLite?

2 Answers 2

18

For this query, you can use group_concat, which directly returns a string:

SELECT ..., group_concat(tk1.TName || ',' || ot.TTime, ' - ')
FROM ...
Sign up to request clarification or add additional context in comments.

4 Comments

it's worth to mention that unlike the ARRAY_AGG function, you must specify the GROUP_BY clause for GROUP_CONTACT, more infos: stackoverflow.com/questions/22190200/…
@younes0 All aggregate functions return a single row without GROUP BY; there's no difference between ARRAY_AGG and GROUP_CONCAT.
You're right; I was talking about the specific case postgres which allows to omit the group_by (if you query in one table I guess)
@younes0 All SQL databases allow to omit the GROUP BY (and then use one group over all rows when you're using any aggregate function).
10

SQLite now has the JSON1 extension (which ships in the default distribution) that can group and create arrays of JSON objects. For example,

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;

The second column will be formatted as a JSON array e.g. [{"tname":...,"ttime":...},...].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.