Click here to Skip to main content
15,886,799 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
i have a table and i want to find out first non-existing date starting from now() to now()+30days. lets assume today is 21.

>| userId |       dates        |
| 1      | 2021-06-22 00:00:00|
| 1      | 2021-06-24 00:00:00|

| 2      | 2021-06-21 00:00:00|
| 2      | 2021-06-22 00:00:00|
| 2      | 2021-06-23 00:00:00|
| 2      | 2021-06-30 00:00:00|

| 3      | 2021-06-23 00:00:00|
| 3      | 2021-06-24 00:00:00|
| 3      | 2021-06-27 00:00:00|
expected output :-

| userId |       dates        |
| 1      | 2021-06-21 00:00:00|
| 2      | 2021-06-24 00:00:00|
| 3      | 2021-06-21 00:00:00|
I'm using postgres. can u help? the data is pretty large


What I have tried:

used lead() but didn't work and taking max min also didn't work.
Posted
Updated 21-Jun-21 21:10pm

1 solution

You can use common table expressions for such of requirements. See:

SQL
WITH RECURSIVE alldays as
(
  -- initial query
  SELECT CAST('2021-06-21' as timestamp without time zone) currdate, 
    CAST('2021-06-21' as timestamp without time zone) + 30 * interval '1 day' maxdate
  -- recursive part
  UNION ALL
  SELECT a.currdate + interval '1 day' currdate, a.maxdate
  FROM alldays a
  WHERE a.currdate + interval '1 day' <= a.maxdate
),
allusers as
(
  SELECT DISTINCT userid
  FROM mydata
)
SELECT u.userid, d.currdate dates
FROM allusers u CROSS JOIN alldays d
WHERE NOT EXISTS
(
  SELECT userid, dates
  FROM mydata md
  WHERE md.userid = u.userid AND md.dates = d.currdate
)
ORDER BY u.userid, d.currdate;


dbfiddle[^]

Note:
Above query returns all missing dates till now + 30 days. Change it to your needs.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900