从组中选择最新日期

时间:2018-08-31 01:26:39

标签: sql sql-server max

我需要在数据库中找到每个记录的最新上诉日期,我尝试使用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]

2 个答案:

答案 0 :(得分:1)

您可以为此使用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]
                                  );

答案 1 :(得分:0)

没有示例数据,我不能肯定地说这是正确的答案,但是我会通过根据您感兴趣的ID获取最大日期并将其作为子查询进行内部连接来实现。如果您需要上诉ID,请换出子查询ID。

NSFetchedResultsController