I want to get the names of the workers that did orders on day x AND day y.
select name
from worker,
orders
where worker.workerid = oders.workerid
and date = x and date = y;
So I want only to get the workers that did orders on both days.
I want to get the names of the workers that did orders on day x AND day y.
select name
from worker,
orders
where worker.workerid = oders.workerid
and date = x and date = y;
So I want only to get the workers that did orders on both days.
in (x,y)
will get you the workers that worked in at least one of the 2 days.
While this one here will get you those who worked 2 distinct days.
group by name
having count(distinct date)=2
In total you get what you want
select name
from worker,
orders
where worker.workerid = oders.workerid
and date in (x,y)
group by name
having count(distinct date)=2
Do a GROUP BY
. Use HAVING
to make sure both dates are there.
select name
from worker
join orders
on worker.workerid = orders.workerid
where date in (x, y)
group by name
having count(distinct date) >= 2
Note the switch to modern, explicit JOIN
syntax!
Using two exists where clauses...
SELECT name
FROM worker AS w
WHERE EXISTS (SELECT 1
FROM orders AS o
WHERE w.workerid = o.workerid
AND date = x)
AND EXISTS (SELECT 1
FROM orders AS o
WHERE w.workerid = o.workerid
AND date = y)
The easiest approach is to use 2 partial queries and the postgre Intersect
operator:
select name
from worker,
orders
where worker.workerid = oders.workerid
and date = y
INTERSECT
select name
from worker,
orders
where worker.workerid = oders.workerid
and date = x;
This will leave only worker names, that have been active at X
AND y
.
http://www.postgresqltutorial.com/postgresql-intersect/
Like the UNION and EXCEPT operators, the PostgreSQL INTERSECT operator combines the result sets of two or more SELECT statements into a single result set. The INTERSECT operator returns any rows that are available in both result set or returned by both queries.
try this:
SELECT name from worker, orders
WHERE worker.workerid = oders.workerid
DATE date IN (x, y)