简体   繁体   English

在同一张桌子上简单的左联接

[英]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 . 我有一张桌子可以叫data This table has a date column and a column that specifies entries as daily data or monthly data. 该表具有date列和将条目指定为daily数据或monthly数据的列。

I want to retrieve all daily records, along with monthly records in which no daily records exist in the month. 我想检索所有的daily记录,以及monthly没有每日记录的monthly记录。 Example: if daily record 2016-01-10 exists, then I do not want to retrieve monthly record on 2016-01-01 示例:如果存在每日记录2016-01-10 ,那么我不想检索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'
    )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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