使用a列作为参考合并表中的行[PSQL]

时间:2019-03-19 04:19:50

标签: psql

我有一个像这样的postgresql表:

| id   | date       | status |
|------|------------|--------|
| id1  | 2019-01-01 | ON     |
| id1  | 2019-01-02 | OFF    |
| id1  | 2019-01-03 | ON     |

如何将行合并成这样:

| id   | on_date    | off_date   |
|------|------------|------------|
| id1  | 2019-01-01 | 2019-01-02 |
| id1  | 2019-01-03 |            |

OFF状态总是插入在ON状态之后(在关闭日期之前有一个打开日期)

我当前的解决方案是:

WITH ons AS (
  SELECT id, row_number() OVER(ORDER BY date) as row_num, date as on_date
  FROM table
  WHERE status = 'ON' AND id = id1),
offs AS (
  SELECT id, row_number() OVER(ORDER BY date) as row_num, date as off_date
  FROM table
  WHERE status = 'OFF' AND id = id1)
SELECT ons.id, ons.on_date, offs.off_date 
FROM ons
LEFT JOIN offs ON ons.id = off.id AND ons.row_num = offs.row_num

我可以使用更简单的查询吗?谢谢。

2 个答案:

答案 0 :(得分:0)

在SQL下方使用:

select tt.id, tt.date as on_date, (select idate from 
table where id=tt.id and status='OFF' and 
date>=tt.idate and rownum<2) as off_date from table tt
where status='ON'

答案 1 :(得分:0)

我认为您可以使用以下查询获得结果:

SELECT id,on_date,off_date from (SELECT id,date as on_date,'' as off_date FROM test WHERE status = 'ON' UNION ALL SELECT id,'' as on_date,date as off_date FROM test WHERE status = 'OFF') as a