使用此查询,我只想显示具有类似PersonPosting和PostDate的最新条目,以便显示最新条目的ID。
表:
Post_ID | PersonPosting | PostDate | StartTime
1 2 2019-09-24 12:30pm
2 2 2019-09-24 12:33pm
3 2 2019-09-25 12:30pm
4 2 2019-09-25 12:33pm
5 1 2019-09-26 2:30pm
6 1 2019-09-26 2:31pm
7 1 2019-09-26 2:32pm
8 1 2019-09-26 2:33pm
我尝试调整子查询以返回StartTime
SELECT
etl.Post_ID, etl.PersonPosting, etl.PostDate, etl.StartTime,
(SELECT MAX (post.PostTime) from [log].[Posts] post2
WHERE post2.PostDate = etl.PostDate AND etl2.PersonPosting = etl.PersonPosting) as Post_ID
FROM log.Posts post
WHERE
group by PostDate, PersonPosting, Post_ID, StartTime
Order By
etl.PostDate DESC,
PersonPosting ASC;
预期结果:
Post_ID | PersonPosting | PostDate | StartTime
2 2 2019-09-24 12:33pm
4 2 2019-09-25 12:33pm
8 1 2019-09-26 2:33pm
错误:
子查询返回的值超过一个。当子查询跟随=、!=、<、<=、>、>=或子查询用作表达式时,这是不允许的。
发布于 2019-09-26 20:33:30
您可以使用带有NOT EXISTS
条件的关联子查询来确保在同一人和日期上不存在其他记录,并且开始时间更长:
SELECT p.*
FROM log.Posts p
WHERE NOT EXISTS (
SELECT 1
FROM posts p1
WHERE
p1.PersonPosting = p1.PersonPosting
AND p1.PostDate = p.PostDate
AND p1.StartTime > p.StartTime
)
在MySQL 8.0中,ROW_NUMBER()
为您提供了一个更短的语法:
SELECT *
FROM (
SELECT
p.*,
ROW_NUMBER() OVER(PARTITION BY PersonPosting, PostDate ORDER BY StartTime DESC) rn
FROM log.Posts p
) x
WHERE rn = 1
发布于 2019-09-26 20:26:19
假设startTime
确实是一段时间,您可以使用关联子查询:
select p.*
from logs.post p
where p.StartTime = (select max(p2.StartTime)
from logs.post p2
where p2.PersonPosting = p.PersonPosting and
p2.PostDate = p.PostDate
);
为了提高性能,您需要logs.post(PersonPosting, PostDate, StartTime)
上的索引。
https://stackoverflow.com/questions/58124245
复制相似问题