简体   繁体   English

SQL Server为每个ID选择最大日期

[英]SQL Server select max date per ID

I am trying to select max date record for each service_user_id for each finance_charge_id and the amount that is linked the highest date 我正在尝试为每个finance_charge_id选择每个service_user_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

The issue is that I receive multiple entries where the amount is different. 问题是我收到金额不相同的多个条目。 I only want to receive the amount on the latest date for each finance_charge_id 我只想收到每个finance_charge_id的最新日期的金额

At the moment I receive the below which is incorrect (the third line should not appear as the 1st line has a higher date) 目前,我收到以下不正确的信息(第三行不应显示,因为第一行的日期较高)

Finance_Charge_ID   (No column name)    Amount
2                      2014-10-19       1.00
3                      2014-10-16       500.00
2                      2014-10-01       1000.00

Remove the Amount column from the group by to get the correct rows. 从组中删除“ Amount列,以获取正确的行。 You can then join that query onto the table again to get all the data you need. 然后,您可以再次将该查询连接到表上,以获取所需的所有数据。 Here is an example using a CTE to get the max dates: 这是使用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

This can be done using a window function which removes the need for a self join on the grouped data: 这可以使用窗口函数来完成,该函数无需对分组数据进行自我联接:

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;

As the window function does not require you to use group by you can add any additional column you need in the output. 由于窗口功能不需要您使用group by您可以在输出中添加所需的任何其他列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM