简体   繁体   English

从组中选择最新日期

[英]Select Most recent dates from a group

I need to find the latest Appeal date for each record in our database, I've tried using Max(date) but it still gives me all of our Constituents rater than just the one row of the latest date I'm using MS SQL 我需要为数据库中的每个记录查找最新的上诉日期,我尝试使用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]

You can use ROW_NUMBER() and TOP (1) WITH TIES for this: 您可以为此使用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);

This assumes that you really mean for each constituent, not for each record. 假设您实际上是针对每个组成部分而不是每个记录。

Another method that might even have better performance with the right indexes is: 使用正确的索引甚至可能具有更好的性能的另一种方法是:

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

Without sample data I cant say for sure this is the correct answer but I would approach it by grabbing the max date based on the ID you are interested in and inner joining it as a sub query. 如果没有样本数据,我不能肯定地说这是正确的答案,但是我会根据您感兴趣的ID来获取最大日期,并将其作为子查询进行内部连接来解决。 Swap out the sub query ID if you need Appeal ID instead. 如果您需要上诉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