简体   繁体   中英

Postgres grouping query result by row

Im new to Postgres and using it now for the first time with nodejs. I got a table with sensor readings (temperature in this case). The Table is something like:

sensorID timestamp temperature
1 8:22pm 22C
2 8:23pm 21C
3 8:25pm 24C
2 8:26pm 27C
2 8:28pm 19C
1 8:31pm 28C

Is there a way to create a single query to get the data to nodejs formatted like this:

[
   {sensorID: 1,
   data: [
      {timestamp:8:22pm, temperature:22C},
      {timestamp:8:31pm, temperature:28C}

   ]},
   {sensorID: 2,
   data: [
      {timestamp:8:23pm, temperature:21C},
      {timestamp:8:26pm, temperature:27C},
      {timestamp:8:28pm, temperature:19C}
   ]},
   {sensorID: 3,
   data: [
      {timestamp:8:25pm, temperature:24C}

   ]}
]

Welcome to SO.

To build and aggregate json objects in PostgreSQL (via SQL) you can use the functions jsonb_build_object and jsonb_agg :

WITH j AS (
  SELECT 
    sensorid,
    jsonb_build_object(
      'data',
       jsonb_agg(
         jsonb_build_object(
           'timestamp',timestamp,
           'temperature',temperature)))
  FROM t
  GROUP BY sensorid
  ORDER BY sensorid) 
SELECT jsonb_agg(j) FROM j;

Demo: db<>fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM