如何使用postgres格式化sql查询中的数据

时间:2017-05-23 06:48:00

标签: sql json postgresql

我有表名:locations

Banguluru, 22,24, Banguluru, 22,25 Banguluru, 22,26 Hyderabad, 22,27

表中的

数据:

{ 
    location: 'Hyderabad',
        positions :  [
            position : {
                lat: 22,
                lng: 27                 
        }]
    },
{
        location: 'Banguluru',
        positions :  [
            position : {
               lat: 22,
                lng: 24                 
        },  position : {
               lat: 22,
                lng: 25
        },  position : {
               lat: 22,
                lng: 26
       }]}

我想要这样的输出:

public int getItemPosition(long id)
{
for (int position=0; position<100; position++)
    if (mList.get(position).getId() == id)
        return position;
return 0;
}  

1 个答案:

答案 0 :(得分:0)

样品:

t=# create table s170 (location text, ltn int,lgn int);
CREATE TABLE
t=# insert into s170 values ('Banguluru',24,25),('Banguluru',24,26),('Hyderabad',22,27);
INSERT 0 3

查询:

t=# with b as (
  with a as (
    select location, (select to_json(position) from (select ltn,lgn) as position) as position
    from s170
  )
  select location,json_agg(position) as position
  from a
  group by location
)
select json_agg(b)
from b;
                                     json_agg
----------------------------------------------------------------------------------
 [{"location":"Hyderabad","position":[{"ltn":22,"lgn":27}]},                     +
  {"location":"Banguluru","position":[{"ltn":24,"lgn":25}, {"ltn":24,"lgn":26}]}]
(1 row)

或漂亮:

[
  {
    "location": "Hyderabad",
    "position": [
      {
        "ltn": 22,
        "lgn": 27
      }
    ]
  },
  {
    "location": "Banguluru",
    "position": [
      {
        "ltn": 24,
        "lgn": 25
      },
      {
        "ltn": 24,
        "lgn": 26
      }
    ]
  }
]

我相信可以很容易地跳过一个CTE包装,但是为了代码清晰,让它在这里

<强>更新 对于9.2应该这样做:

t=# with b as (
  with a as (
    select location, (select row_to_json(position,true) from (select ltn,lgn) as position) as position
    from s170
  )
  select location,string_agg(position::text,',') as position
  from a
  group by location
)
select string_agg(concat('{"location":"',location,'","position":[',position,']}'), ',')
from b;
string_agg
{"location":"Hyderabad","position":[{"ltn":22,
 "lgn":27}]},{"location":"Banguluru","position":[{"ltn":24,
 "lgn":25},{"ltn":24,
 "lgn":26}]}
(1 row)