Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

sql - How to transform this data in PostgreSQL

How do I transform this data

Date1 Date2 ID
2021-01-01 2021-01-04 1
2021-01-05 2021-01-25 2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You intuition is correct, and a calendar table approach should work here:

WITH dates AS (
    SELECT date_trunc('day', dt)::date AS dt
    FROM generate_series (
        '2021-01-01'::timestamp,
        '2021-01-31'::timestamp,
        '1 day'::interval) dt
)

SELECT d.dt AS Date, t.ID
FROM dates d
LEFT JOIN yourTable t
    ON d.dt BETWEEN t.Date1 AND t.Date2;

Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...