SQL Server Group By和内部联接一起按最大日期获取唯一值

siv3szwd  于 2023-01-20  发布在  其他
关注(0)|答案(1)|浏览(154)

这里有一个表,我想在SQL Server中在其中编写一个SELECT查询,该查询允许我获得以下内容:

  • 对于SalesPerson x Country的每个唯一组合,仅获取Upload_DateTime最新的行

然而,我尝试做一个group-by和inner join,但是没有用。我的代码如下:

SELECT t1.[SalesPerson], t1.[Country], MAX(t1.[Upload_DateTime]) as [Upload_DateTime]
  FROM [dbo].[CommentTable] AS t1
   GROUP BY t1.[SalesPerson], t1.[Country] 
  INNER JOIN SELECT * FROM [dbo].[CommentTable] as t2 ON t1.[SalesPerson] = t2.[SalesPerson], t1.[Country] = t2.[Country]

看起来GROUP BY需要在INNER JOIN之外完成?这是如何工作的?当我运行查询时,我得到了一个错误,似乎我的SQL不正确。

xcitsw88

xcitsw881#

基本上,这个子查询将获取人员、国家和最新日期:

SELECT 
SalesPerson, Country, MAX(uplodaed_datetime)
FROM CommentTable
GROUP BY SalesPerson, Country;

这可以用在很多方面(例如,JOININ子句)。
主查询会将剩余的列添加到结果中。
因为您尝试了JOIN,所以这里是JOIN选项:

SELECT
c.id, c.SalesPerson, c.Country,
c.Comment, c.uplodaed_datetime
FROM 
CommentTable AS c
INNER JOIN 
(SELECT 
SalesPerson, Country, 
MAX(uplodaed_datetime) AS uplodaed_datetime
FROM CommentTable
GROUP BY SalesPerson, Country) AS sub
ON c.SalesPerson = sub.SalesPerson
AND c.Country = sub.Country
AND c.uplodaed_datetime = sub.uplodaed_datetime
ORDER BY c.id;

试用:db<>fiddle

相关问题