我想创建一个包含表中所有最新数据的行,我找到了对每一列分别进行处理的方法,是否可以在一个查询中进行处理?
这是想要的答案表:
答案 0 :(得分:1)
您可以使用 correlated 子查询:
select t.*
from table t
where time1 = (select max(t1.time1) from table t1 where t1.p_id = t.p_id);
答案 1 :(得分:1)
如果需要与max_daye相关的行 您可以将子查询的联接与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
或者如果您只需要每个p_id的最大值,则可以使用
select m.p_id, max(m.aaa), max(m.bbb), max(m.ccc )
from mytable m
group by m-p_id
答案 2 :(得分:0)
您可以使用相关子查询为每个不同的ID提取每一列的“最新”非null值。
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;