简体   繁体   中英

Get Statistical data from table in PostgreSQL using single query

I am using PostgreSQL database, I have the requirement where I have to provide statistical data for the configurable timespan. I have pasted the sample data of my table.

**id   timeStamp        caseId**  
224 2017-05-30 12:47:27 4654
226 2017-05-30 1:59:46  5165
225 2017-05-30 1:53:31  4658
223 2017-05-30 2:44:45  4656
221 2017-05-30 4:05:53  4645
220 2017-05-30 6:05:12  4640

if the time span is 1 hour then, I want the count records for each hour like [1,2,1,0,1,0,1] and so on...

I can do that using 12 different query with start and end date. but I want the output in one query.

Is it possible in one query.?

You can use an outer join with a table function that produces the hours you want to query.

This assumes that your table is called incidents :

SELECT hours.h, count(i)
FROM incidents i
   RIGHT JOIN generate_series(
                 TIMESTAMP '2017-05-30 00:00:00',
                 TIMESTAMP '2017-05-30 23:00:00',
                 INTERVAL '1 hour'
              ) hours(h)
      ON i.timestamp >= hours.h
         AND i.timestamp < hours.h + INTERVAL '1 hour'
GROUP BY hours.h;

If you want the result as an array, omit hours.h from the SELECT list and surround the query with

SELECT array_agg(count)
   FROM (...) q;

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