I'm want to create one row that includes all the latest data from my table, I found the way to do it separately for each column, is it possible to do it in one query?
This will be the wanted answer table:
I'm want to create one row that includes all the latest data from my table, I found the way to do it separately for each column, is it possible to do it in one query?
This will be the wanted answer table:
You can use correlated subquery :
select t.*
from table t
where time1 = (select max(t1.time1) from table t1 where t1.p_id = t.p_id);
if you need the rows related to max_daye you could use a join with the subquery for max time1
select m.p_id, m.aaa, m.bbb, m.ccc
from mytable m
inner join (
SELECT p_id, max(time1) max_date
FROM mytable
group by p_id
) t on t.max_date = m.time1 and t.p_id = m.p_id
or if you need only the max vale for each p_id you can use
select m.p_id, max(m.aaa), max(m.bbb), max(m.ccc )
from mytable m
group by m-p_id
You could use correlated subqueries fetching the "latest" non null values for each column for each distinct ID.
SELECT t1.p_id,
(SELECT t2.aaa
FROM elbat t2
WHERE t2.p_id = t1.p_id
AND t2.aaa IS NOT NULL
ORDER BY t2.time1 DESC
LIMIT 1) aaa,
...
(SELECT t2.ccc
FROM elbat t2
WHERE t2.p_id = t1.p_id
AND t2.ccc IS NOT NULL
ORDER BY t2.time1 DESC
LIMIT 1) ccc,
FROM (SELECT DISTINCT
p_id
FROM elbat) t1;