我有一张这样的表:
Id,Comment,LastUpdatedDate
我正在选择该ID的最新评论。该表可以对该ID具有不同日期的许多评论,但我正在尝试获取最新日期。我试过以下但没有成功:
SELECT tt.*
FROM tagtestresultcomment tt
INNER JOIN
(
SELECT tag_id, MAX(last_update) AS MaxDateTime
FROM tagtestresultcomment
GROUP BY tag_id
) groupedtt ON tt.tag_id = groupedtt.tag_id AND tt.last_update = groupedtt.MaxDateTime
order by tag_id
有没有人对如何实现这一点有任何想法?
谢谢!
答案 0 :(得分:2)
试试这个
Select * from tagtestresultcomment where last_update in
(select max(last_update) from tagtestresultcomment group by tag_id)
答案 1 :(得分:1)
您的查询代码过于冗余。第一
tt.tag_id = groupedtt.tag_id AND tt.last_update = groupedtt.MaxDateTime
这就够了
tt.tag_id = groupedtt.tag_id
第二,它就够了
SELECT [desired field list extcept last_update and ],
tag_id,
MAX(last_update) AS MaxDateTime
FROM
tagtestresultcomment
group by
tag_id, [desired field list extcept last_update and tag_id]
完全实现你的目标
答案 2 :(得分:1)
听起来你只想要每个 tag_id的最新评论?在这种情况下,您可以使用SQL 2005中的一种方法:
;WITH CTE AS
(
SELECT *,
ROW_NUMBER() OVER(PARTITION BY tag_id ORDER BY last_update DESC) AS RowNo
FROM TagTestResultComment
)
SELECT * FROM CTE WHERE RowNo = 1
答案 3 :(得分:0)
我尝试过这样的事情:
declare @tagtestresultcomment table
(
id int
, comment varchar(50)
,LastUpdatedDate datetime
)
--==== Populate table
insert into @tagtestresultcomment(id,comment,LastUpdatedDate)
select 1,'My name is Arthur','2011-06-09 00:00:00' union all
select 2,'My name is DW','2011-06-19 00:00:00' union all
select 2,'Arthur is my brother','2011-06-21 00:00:00' union all
select 1,'I have a sister named DW','2011-06-21 00:00:00' union all
select 3,'I am Muffy','2011-06-14 00:00:00' union all
select 3,'I like sports','2011-06-14 00:00:00'
-- SELECT stmt
select * from @tagtestresultcomment t
join
(
select id, MAX(lastupdateddate) as LastUpdatedDate from @tagtestresultcomment group by id
) m
on t.id = m.id
and t.LastUpdatedDate = m.LastUpdatedDate
答案 4 :(得分:0)
“ MAX”组功能不适用于我,因此我使用了子查询。我无法将您的注意力集中在单个表的示例上,因此我将一个常见的父子一对多关系与一个博客和评论表作为示例。
SELECT
b.id,
b.content,
c.id,
c.blog_id,
c.content,
c.last_update
FROM blog b
INNER JOIN blog_comment c
ON b.id = c.blog_id AND c.id = (
SELECT TOP 1 id FROM blog_comment WHERE blog_id = b.id ORDER BY last_update DESC
)
该查询对我的子查询产生了影响,因为它将为博客表中的每个记录调用“ SELECT TOP 1”查询。我希望听到一个更快,更高效的示例。