如何检索第三个最近的日期分组另一列?

时间:2014-06-05 19:28:08

标签: sql-server sql-server-2005

编辑:我正在使用SQL Server 2005

所以这是一个棘手的问题。出于审计目的,我们需要尝试3次联系客户。我们可以超过3次尝试超越,但审计目的我需要检索每个客户的第三次最近尝试的日期。

在大多数情况下,你只需要最近一段时间,所以你可以做类似的事情。

SELECT CustID,MAX(AttemptDate) FROM Attempts GROUP BY CustID

..但在这种情况下显然不起作用。

假设我有一个与客户绑定的尝试表。

CustID    AttemptDate
123       2014-01-02
123       2014-01-05
123       2014-01-06 * retrieve this one
123       2014-01-07
123       2014-01-10
555       2014-02-01
555       2014-02-03
555       2014-02-07 * retrieve this one
555       2014-02-12
555       2014-02-20

输出:

CustID    AttemptDate
123       2014-01-06
555       2014-02-07

任何关于解决此问题的提示?

2 个答案:

答案 0 :(得分:2)

;WITH t AS (
  SELECT *,
    ROW_NUMBER() OVER(PARTITION BY CustId ORDER BY AttemptDate DESC) AS nth_most_recent
  FROM MyTable
)
SELECT *
FROM t
WHERE nth_most_recent = 3

答案 1 :(得分:1)

ROW_NUMBER排名功能是您的朋友:

  WITH cte (CustId, AttemptDate, AttemptNumber) AS (
    SELECT 
      CustId,
      AttemptDate,
      ROW_NUMBER() OVER (PARTITION BY CustID ORDER BY AttemptDate DESC) AS AttemptNumber
    FROM Attempts
  )
  SELECT 
    CustId,
    AttemptDate
  FROM cte
  WHERE AttemptNumber = 3

或者,如果公用表表达式语法导致问题,则可以使用子查询:

  SELECT
    CustId,
    AttemptDate
  FROM (
    SELECT 
      CustId,
      AttemptDate,
      ROW_NUMBER() OVER (PARTITION BY CustID ORDER BY AttemptDate DESC) AS AttemptNumber
    FROM Attempts
  ) sq
  WHERE AttemptNumber = 3