簡體   English   中英

從組中選擇最新日期

[英]Select Most recent dates from a group

我需要為數據庫中的每個記錄查找最新的上訴日期,我嘗試使用Max(date),但它仍然為我提供了所有成分評估者,而不僅僅是我使用MS SQL的最新日期的一行

    SELECT 
    [Constituent ID]
      ,[Assigned Appeal Category]
      ,[Assigned Appeal ID]**strong text**
      ,[Assigned Appeal Response]
      ,MAX([Assigned Appeal Date])


  FROM [FHF_MarketingData].[dbo].[FHF_Constituent_Appeals]

  WHERE [Assigned Appeal Category] = 'TELEMARKETING'



GROUP BY 
    [Constituent ID],
    [Assigned Appeal Category],
    [Assigned Appeal ID],
    [Assigned Appeal Response],
    [Assigned Appeal Date]

您可以為此使用ROW_NUMBER()TOP (1) WITH TIES

SELECT TOP (1) WITH TIES ca.*
FROM [FHF_MarketingData].[dbo].[FHF_Constituent_Appeals] ca
WHERE ca.[Assigned Appeal Category] = 'TELEMARKETING'
ORDER BY ROW_NUMBER() OVER (PARTITION BY [Constituent ID] ORDER BY [Assigned Appeal Date] DESC);

假設您實際上是針對每個組成部分而不是每個記錄。

使用正確的索引甚至可能具有更好的性能的另一種方法是:

SELECT ca.*
FROM [FHF_MarketingData].[dbo].[FHF_Constituent_Appeals] ca
WHERE ca.[Assigned Appeal Category] = 'TELEMARKETING' AND
      ca.[Assigned Appeal Date] = (SELECT MAX(ca2.[Assigned Appeal Date])
                                   FROM [FHF_MarketingData].[dbo].[FHF_Constituent_Appeals] ca2
                                   WHERE ca2.[Constituent ID] = ca.[Constituent ID] AND
                                         ca2.[Assigned Appeal Category] = ca.[Assigned Appeal Category]
                                  );

如果沒有樣本數據,我不能肯定地說這是正確的答案,但是我會根據您感興趣的ID來獲取最大日期,並將其作為子查詢進行內部連接來解決。 如果您需要上訴ID,請交換子查詢ID。

 SELECT [Constituent ID]
        ,[Assigned Appeal Category]
        ,[Assigned Appeal ID]
        ,[Assigned Appeal Response]
        ,MaxDt
    FROM [FHF_MarketingData].[dbo].[FHF_Constituent_Appeals] CA
    INNER JOIN (
        SELECT  MAX([Assigned Appeal Date]) MaxDT
            ,[Constituent ID]
        FROM [FHF_MarketingData].[dbo].[FHF_Constituent_Appeals]
        WHERE [Assigned Appeal Category] = 'TELEMARKETING'
        GROUP BY [constituent id]
        ) MaxDt ON MaxDt.[Constituent ID] = CA.[Constituent ID]

暫無
暫無

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

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