Sql 为每个参数选择第一个结果

Sql 为每个参数选择第一个结果,sql,greatest-n-per-group,Sql,Greatest N Per Group,我有一张表,上面有账号、账号和日期 我试图获取每个帐户的最新代码,但group by为每个帐户提供了多个观察结果,因此我甚至无法使用first/top语句 例如: account\u id account\u属性\u code current\u att\u date 1 579 01.01.2005 1 254 01.02.2006 1

我有一张表,上面有账号、账号和日期 我试图获取每个帐户的最新代码,但group by为每个帐户提供了多个观察结果,因此我甚至无法使用first/top语句

例如:

account\u id account\u属性\u code current\u att\u date
1                579                      01.01.2005
1                254                      01.02.2006
1                366                      10.10.2018
2                748                      01.07.2008
2                766                      08.05.2009
2                205                      07.06.2014
选择
帐户id,
账户\属性\代码,
最大值(帐户属性更新日期)为当前截止日期
从我的桌子上
按帐户Id分组,
帐户\属性\代码

我希望每个帐户只有一行,其属性代码中的日期是最新的。

在SQL Server上,我将使用:

SELECT TOP 1 WITH TIES
    account_id, Account_Attribute_Code, Account_Attribute_Update_Date
FROM my_table
ORDER BY
    ROW_NUMBER() OVER (PARTITION BY account_id
                       ORDER BY Account_Attribute_Update_Date DESC);

在SQL Server上,我将使用:

SELECT TOP 1 WITH TIES
    account_id, Account_Attribute_Code, Account_Attribute_Update_Date
FROM my_table
ORDER BY
    ROW_NUMBER() OVER (PARTITION BY account_id
                       ORDER BY Account_Attribute_Update_Date DESC);

您可以只使用相关子查询:

select t.*
from t
where t.Account_Attribute_Update_Date = (select max(t2. Account_Attribute_Update_Date)
                                         from t t2
                                         where t2.account_id = t.account_id
                                        );
解决这个问题有多种方法。如果索引位于
(帐户id、帐户属性\u更新\u日期)
,则这通常具有最佳性能


一个警告:如果一个帐户有重复的最长日期,您将得到多行。

您可以使用一个相关的子查询:

select t.*
from t
where t.Account_Attribute_Update_Date = (select max(t2. Account_Attribute_Update_Date)
                                         from t t2
                                         where t2.account_id = t.account_id
                                        );
解决这个问题有多种方法。如果索引位于
(帐户id、帐户属性\u更新\u日期)
,则这通常具有最佳性能

一个警告:如果一个帐户有重复的最长日期,您将得到多行。

您可以使用row\u number()函数

可以使用row_number()函数

你提到“顶级”。。。您正在使用SQL Server吗?请参阅您提到的“top”。。。您正在使用SQL Server吗?请参阅