Alexander Sung
Alexander Sung

Reputation: 325

Simple left join on same table

I am having trouble building a query that would accomplish something relatively simple.

I have one table we can call data. This table has a date column and a column that specifies entries as daily data or monthly data.

I want to retrieve all daily records, along with monthly records in which no daily records exist in the month. Example: if daily record 2016-01-10 exists, then I do not want to retrieve monthly record on 2016-01-01

I feel like this following query should be accomplishing this goal, but I cannot figure out why it's returning too many rows (duplicates) and when deduped, is not returning the desired set.

SELECT daily.* 
FROM data daily 
LEFT JOIN data monthly 
    ON date_trunc('month', daily.date) != date_trunc('month', monthly.date) 
AND monthly.interval='monthly' 
WHERE daily.interval='daily' 
    AND monthly.interval='monthly'

Intended behaviour is to return all records from the left, daily data, and join on the condition in which no monthly records are returned that have the same month as any daily records.

Upvotes: 2

Views: 1036

Answers (2)

Periklis Douvitsas
Periklis Douvitsas

Reputation: 2491

Can you try the following query and tell me if this works for you

SELECT monthly.* 
FROM data monthly 
 where monthly.interval='monthly' and to_char(monthly.date, 'YYYY-MM') not in 
(select to_char(daily.date, 'YYYY-MM') from data daily where daily.interval='daily' ) 
UNION
SELECT daily.* 
FROM data daily 
 where daily.interval='daily'

Upvotes: 1

Clodoaldo Neto
Clodoaldo Neto

Reputation: 125284

select *
from data d
where
    interval = 'daily'
    or
    interval = 'monthly'
    and
    not exists (
        select 1 from data
        where
            date_trunc('month', d.date) = date_trunc('month', date)
            and interval = 'daily'
    )

Upvotes: 2

Related Questions