How can I return one row for every row appearing in Table1 (dps) joining columns from Table2(dsd) in case they exist?
The join can be done with x, y , id (dsd.id can be NULL on Table2).
For every x,y pair can be more than one id.
I need to filter by a time range with time column only appearing in Table2 (dsd).
I added s.time IS NULL in the WHERE clause because there are not rows in Table2 (dsd) for every row in Table1 (dps). But I would like to remove rows in Table2 where the dsd.time IS NULL.
SELECT
s.time
, dps.x
, dps.y
, dps.id AS metric
, dps.anzahl AS produced
, s.read_tags AS read_tags
FROM
dps
LEFT JOIN
(SELECT MAX(dsd.time) AS time, dsd.x, dsd.y, dsd.id, COUNT(DISTINCT dsd.tagid) AS read_tags
FROM dsd
WHERE (time IS NOT NULL)
GROUP BY dsd.x, dsd.y, dsd.id
) AS s
ON ( s.x = dps.x AND s.y = dps.y AND (s.id = dps.id OR s.id IS NULL) )
WHERE s.time BETWEEN valueA AND valueB
OR s.time IS NULL
ORDER BY s.time
Maybe a different type of join is better?
EDIT: now I just need to filter the results by min&max of s.x and s.y of the s query, so I only get results within the time range (for those cases where s.time is NULL). So dps.x should be between MIN(s.x) and MAX(s.x) and the same for dps.y