简体   繁体   中英

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.

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'
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'
    )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM