I have the following tables:
CREATE TABLE Company (
CompanyUniqueID BIGSERIAL PRIMARY KEY NOT NULL,
Name VARCHAR (150) NOT NULL
);
CREATE TABLE Item (
ItemUniqueID BIGSERIAL PRIMARY KEY NOT NULL,
CompanyUniqueID BIGINT NULL REFERENCES company DEFERRABLE INITIALLY DEFERRED,
Name VARCHAR (150) NOT NULL,
AddedDate TIMESTAMP without time zone DEFAULT now()
);
In the life time of the application new companies and items are added to the tables. I wish to create an sql query that will select the "new added companies" from a given date I've started with this query:
(Select * from company
where companyuniqueid in (
select distinct companyuniqueid from Item where AddedDate > '2014-10-25'))
The above is not good because items that were added after 2014-10-25 and belong to companies that already exist will be also selected.
For example, a snapshot of Company
table from 2014-10-20 can look like this:
1 AAA
2 BBB
3 CCC
and table Items will look like:
1 1 111 2014-10-01
2 2 222 2014-10-10
3 2 333 2014-10-10
4 3 444 2014-10-15
on the 2014-10-26 the following records were added:
table company
4 DDD
table Items
5 1 555 2014-10-26
6 3 663 2014-10-26
7 4 777 2014-10-27
I've tried adding this to the query:
(Select * from company
where companyuniqueid in (
select distinct companyuniqueid from Item
where AddedDate > '2014-10-25')
and companyuniqueid not in (
select distinct companyuniqueid from Item
where AddedDate <= '2014-10-25'))
but I'm getting an empty result, what should be the query in order to receive only 4 DDD?