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

问题描述 投票:0回答:2

我有一个带有account_number,account_code和code_date的表我正在尝试获取每个帐户的最新代码,但是group by为我提供了对每个帐户的多次观察,因此我什至不能使用first / top语句。

示例:

account_id  Account_Attribute_Code   current_att_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
 SELECT 
       account_id, 
       Account_Attribute_Code,
       Max(Account_Attribute_Update_Date) AS current_att_date
 FROM my_table
 GROUP BY Account_Id, 
          Account_Attribute_Code

我只希望每个帐户只有一行,并且他的attribute_code的日期是最新的。

sql greatest-n-per-group
2个回答
0
投票
在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);


0
投票
您可以只使用相关的子查询:

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 );

有多种方法可以解决此问题。如果索引为(account_id, Account_Attribute_Update_Date),则通常具有最佳性能。

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


0
投票
您可以使用row_number()函数

SELECT account_id, Account_Attribute_Code, current_att_date, ROW_NUMBER() OVER (PARTITION BY account_id ORDER BY Account_Attribute_Update_Date DESC) as rn FROM my_table where rn=1

© www.soinside.com 2019 - 2024. All rights reserved.