从两列中选择数据作为一列中的数组排序并在另一列中进行分组

时间:2016-07-22 11:20:04

标签: sql arrays postgresql

我的表格如下:

CREATE TABLE IF NOT EXISTS "points" (
    "id" INTEGER NOT NULL,
    "lat" DOUBLE PRECISION NOT NULL,
    "lon" DOUBLE PRECISION NOT NULL
);

INSERT INTO "points" ("id", "lat", "lon") VALUES
    (1,51.11,-0.11),
    (2,51.12,-0.12),
    (3,51.13,-0.13),
    (4,51.14,-0.14),
    (5,52.44,-2.44),
    (6,52.45,-2.45),
    (7,52.46,-2.46),
    (8,52.47,-2.47);

如何从两列(latlon)中选择数据作为表中的JSON数组,并在一列(id)中进行排序? 结果应该是:

[
    [51.11,-0.11],[51.12,-0.12],
    [51.13,-0.13],[51.14,-0.14],
    [44,-2.44],[52.45,-2.45],
    [52.46,-2.46],[52.47,-2.47]
]

1 个答案:

答案 0 :(得分:1)

select to_json(array_agg(array[lat,lon] order by id))
from points
;
                                                      to_json                                                      
-------------------------------------------------------------------------------------------------------------------
 [[51.11,-0.11],[51.12,-0.12],[51.13,-0.13],[51.14,-0.14],[52.44,-2.44],[52.45,-2.45],[52.46,-2.46],[52.47,-2.47]]