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
2.2k views
in Technique[技术] by (71.8m points)

Filling in dates using SQL

I am trying to query a data set where I can get a full count of status on a given set of days. The data would look like this

Customer ID   Status     Date
1             pending    2020-01-01
1             shipped    2020-01-04
1             delivered  2020-01-06

The problem is the status needs to carry over to each of the preceding days so I can sum all status' at the end. So in a perfect world the data would look like this

Customer ID    Status    Date
1              pending   2020-01-01
1              pending   2020-01-02
1              pending   2020-01-03
1              shipped   2020-01-04
1              shipped   2020-01-05
1              delivered 2020-01-06

This would allow me to sum the data set appropriately at the end of the query. I have a table of dates I can join to, but I am struggling to figure out how to fill in the dates that fall between the status changes.

Thanks


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

1 Answer

0 votes
by (71.8m points)

You have the dates table then you need to use lead analytical function join it as follows:

Select t.customerid, t.status, d.date
  From (select lead(date) over (partition by customerid order by date) as ldate from your_table t) t
  Join date_table d
    On (d.date >= t.date and d.date < t.ldate) 
    or (t.ldate is null and t.date = d.date)

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

...