[英]SQL Server - How to have non-aggregated columns in Select statement when using group by?
I want the MAX(Date)
for each distinct ID. 我想要每个唯一ID的
MAX(Date)
。 This is easy: 这很容易:
SELECT
Id,
MAX(LastModifiedDate)
FROM
[MyServer].[Database].[Table]
GROUP BY
Id;
but I also need to include other columns like first name, last name, company, etc. which cannot be aggregated, and it won't work if I put them in the GROUP BY
clause, because then it returns rows I don't want. 但我还需要包括其他无法汇总的列,例如名字,姓氏,公司等,并且如果我将它们放在
GROUP BY
子句中将不起作用,因为这将返回我不想要的行。
In order to do this, instead of using group by, try over(): 为此,请尝试使用over()而不是group by:
select Id, <any other thing you want>,max(LastModifiedDate) over (partition by Id) as LastModifiedDate
FROM [MyServer].[Database].[Table];
Use that query to filter with the same table by ID and that last modified date. 使用该查询通过ID和上次修改日期对同一表格进行过滤。
SELECT
T.*
FROM
[MyServer].[Database].[Table] AS T
INNER JOIN (
select Id,
MAX(LastModifiedDate) AS MaxLastModifiedDate
FROM [MyServer].[Database].[Table]
group by Id
) AS N ON
T.Id = N.Id AND
N.MaxLastModifiedDate = T.LastModifiedDate
EDIT : If you have multiple max dates for each ID, then you can't use their value to filter. 编辑 :如果每个ID有多个最大日期,则不能使用它们的值进行过滤。 You can use a
ROW_NUMBER
to rank them instead: 您可以使用
ROW_NUMBER
进行排名:
;WITH MaxByRowNumber AS
(
SELECT
T.*,
LastModifiedDateRanking = ROW_NUMBER() OVER (PARTITION BY T.ID ORDER BY T.LastModifiedDate DESC)
FROM
[MyServer].[Database].[Table] AS T
)
SELECT
M.*
FROM
MaxByRowNumber AS M
WHERE
M.LastModifiedDateRanking = 1
You might want to add another column to the ORDER BY
to untie the most recent updated dates, or not, depending on your needs. 您可能需要根据需要将另一列添加到
ORDER BY
以解开最近更新的日期。
Figured this out literally as soon as I posted it. 我一经发布便立即弄清了这一点。 I was just confused on the proper way to use a window function.
我只是对使用窗口函数的正确方法感到困惑。
SELECT [Id]
,LastModifiedDate
,Row_Number() over (Partition by Id order by LastModifiedDate DESC) as rn
,[FirstName]
,[LastName]
,[Company]
,[Title]
FROM [MyServer].[Database].[Table] as C
where rn = 1
What i was trying to do was: 我想做的是:
,Row_Number() over (Partition by Id order by MAX(LastModifiedDate) DESC) as rn
but MAX makes no sense because it is DESC 但是MAX没有意义,因为它是DESC
You can use subquery
: 您可以使用
subquery
:
select t.*
from table t
where LastModifiedDate = (select max(t1.LastModifiedDate)
from table t1
where t1.id = t.id
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.