简体   繁体   中英

Return the first and last value from one column when value from another column changes

I am trying to write a PostgreSQL query to return the first and last dates corresponding to indices. I have a table:

Datetime Index
March 1 2021 0
March 2 2021 0
March 3 2021 0
March 4 2021 1
March 5 2021 1
March 6 2021 2

In this case, I would want to return: 在此处输入图像描述

I am wondering how I would write the PostgreSQL query for this.

I think this can be done with the following:

SELECT MIN("Datetime") AS Start
     , MAX("Datetime") AS End
     , "Index"
  FROM <your_table>
 GROUP BY "Index"
 ORDER BY "Index"
;

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