按一定数量将行拆分为列

Split rows to columns by certain number

我在 table 中有以下行:

dates
------------
"2021-01-02"
"2021-01-03"
"2021-01-11"
"2021-01-14"
...

我知道这些行显示日期范围。 因此,第一行是范围开始,下一行是范围结束。下一行是重新开始的范围等等(行数 mod 2 = 0)。

有没有办法select如table:

range_start  | range_end
-------------+-------------
"2021-01-02"   "2021-01-03"
"2021-01-11"   "2021-01-14"
...            ...

?

PostgreSQL 版本为 10.17

这应该有效:

WITH ordered_table AS (
  SELECT
    dates,
    ROW_NUMBER () OVER (ORDER BY dates) AS creation_order
  FROM your_table
)
SELECT
  t1.dates AS range_start,
  t2.dates AS range_end
FROM
  ordered_table t1
INNER JOIN ordered_table t2 ON t2.creation_order = t1.creation_order + 1
WHERE (t1.creation_order % 2) = 1 -- counting from 1

更多详情:

row_number() 使用条件聚合:

select min(date), max(date)
from (select t.*, row_number() over (order by date) as seqnum
      from t
     ) t
group by ceiling(seqnum / 2.0)