Question

I have a table of subscriptions for contacts. A contact can have multiple subscriptions:

CREATE TABLE contact (
    id INTEGER NOT NULL,
    name TEXT,
    PRIMARY KEY (id)
);

CREATE TABLE subscription (
    id INTEGER NOT NULL,
    contact_id INTEGER NOT NULL REFERENCES contact(id),
    start_date DATE,
    end_date DATE,
    PRIMARY KEY (id)
);

I need to get all subscriptions for a given by contact that do not have a subscription that starts on the same date as the end date of the another subscription for the same contact.

So for the given data:

INSERT INTO contact (id, name) VALUES 
(1, 'John'),
(2, 'Frank');

INSERT INTO subscription (id, contact_id, start_date, end_date) VALUES 
(1, 1, '2012-01-01', '2013-01-01'),
(2, 1, '2013-01-01', '2014-01-01'),
(3, 2, '2012-01-01', '2012-09-01'),
(4, 2, '2013-01-01', '2014-01-01');

I want to get subscriptions with ids of 2, 3, 4 but not 1, because the contact 'John' has a subscription with a start_date on the same day (2013-01-01) as the end_date for subscription with id of 1.

What is the best way to achieve this?

Was it helpful?

Solution

SQL Fiddle

select *
from subscription s0
where not exists (
    select 1
    from subscription s1
    where
        s0.contact_id = s1.contact_id
        and s1.start_date = s0.end_date
)
order by contact_id, id
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top