SQL-MySQL:GROUP BY和聚集函数

dohp0rv5  于 2023-01-20  发布在  Mysql
关注(0)|答案(1)|浏览(136)

假设我有一个mysql数据库,其中的表包含以下字段:-id -titre -status -description -priorite
我可以编写什么查询来按状态对数据进行分组并具有以下输出:
[ { status: "open", data: [ {titre: '...', description: '...', priorite: '...'}, {titre: '...', description: '...', priorite: '...'}, {titre: '...', description: '...', priorite: '...'}, {titre: '...', description: '...', priorite: '...'}, ] }, { status: "inprogress", data: [ {titre: '...', description: '...', priorite: '...'}, {titre: '...', description: '...', priorite: '...'}, {titre: '...', description: '...', priorite: '...'}, {titre: '...', description: '...', priorite: '...'}, ] }, { status: "close", data: [ {titre: '...', description: '...', priorite: '...'}, {titre: '...', description: '...', priorite: '...'}, {titre: '...', description: '...', priorite: '...'}, {titre: '...', description: '...', priorite: '...'}, ] } ]
我想知道如何才能做到这一点,我尝试了GROUP_CONCAT和CONCAT,但未以预期格式返回数据

qv7cva1a

qv7cva1a1#

我找到了一个使用JSON_ARRAYAGG和JSON_OBJECT函数的解决方案
我的查询如下所示:

SELECT status, JSON_ARRAYAGG(JSON_OBJECT('title',title,'description', description,'priority', priority)) AS data FROM tasks WHERE (week(createdAt, 1) = week(now()) AND year(createdAt) = year(now())) GROUP BY status ORDER BY status ASC

相关问题