SQL Server选择每个ID的最大日期
我正在尝试为每个服务\用户\ id为每个财务\费用\ id和链接到最高日期的金额选择最大日期记录SQL Server选择每个ID的最大日期,sql,sql-server,greatest-n-per-group,Sql,Sql Server,Greatest N Per Group,我正在尝试为每个服务\用户\ id为每个财务\费用\ id和链接到最高日期的金额选择最大日期记录 select distinct s.Finance_Charge_ID, MAX(s.start_date), s.Amount from Service_User_Finance_Charges s where s.Service_User_ID = '156' group by s.Finance_Charge_ID, s.Amount 问题是我收到多
select distinct
s.Finance_Charge_ID, MAX(s.start_date), s.Amount
from
Service_User_Finance_Charges s
where
s.Service_User_ID = '156'
group by
s.Finance_Charge_ID, s.Amount
问题是我收到多个金额不同的条目。我只想在每个财务费用id的最晚日期收到金额
目前我收到的以下内容不正确(第三行不应出现,因为第一行的日期更高)
从分组依据中删除
Amount
列以获得正确的行。然后,您可以再次将该查询连接到表中,以获取所需的所有数据。以下是使用CTE获取最大日期的示例:
WITH MaxDates_CTE (Finance_Charge_ID, MaxDate) AS
(
select s.Finance_Charge_ID,
MAX(s.start_date) MaxDate
from Service_User_Finance_Charges s
where s.Service_User_ID = '156'
group by s.Finance_Charge_ID
)
SELECT *
FROM Service_User_Finance_Charges
JOIN MaxDates_CTE
ON MaxDates_CTE.Finance_Charge_ID = Service_User_Finance_Charges.Finance_Charge_ID
AND MaxDates_CTE.MaxDate = Service_User_Finance_Charges.start_date
这可以使用一个窗口函数来完成,该函数消除了对分组数据进行自连接的需要:
select Finance_Charge_ID,
start_date,
amount
from (
select s.Finance_Charge_ID,
s.start_date,
max(s.start_date) over (partition by s.Finance_Charge_ID) as max_date,
s.Amount
from Service_User_Finance_Charges s
where s.Service_User_ID = 156
) t
where start_date = max_date;
由于窗口功能不要求您使用
分组依据
,您可以在输出中添加所需的任何附加列。如果它们是两行,且具有相同的财务费用ID和开始日期值,该怎么办?
select Finance_Charge_ID,
start_date,
amount
from (
select s.Finance_Charge_ID,
s.start_date,
max(s.start_date) over (partition by s.Finance_Charge_ID) as max_date,
s.Amount
from Service_User_Finance_Charges s
where s.Service_User_ID = 156
) t
where start_date = max_date;