簡體   English   中英

SQL Server為每個ID選擇最大日期

[英]SQL Server select max date per ID

我正在嘗試為每個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

問題是我收到金額不相同的多個條目。 我只想收到每個finance_charge_id的最新日期的金額

目前,我收到以下不正確的信息(第三行不應顯示,因為第一行的日期較高)

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

從組中刪除“ 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;

由於窗口功能不需要您使用group by您可以在輸出中添加所需的任何其他列。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM