SQL HELP在尝试获取记录的最大值(日期)时获取重复项

时间:2016-08-15 17:02:04

标签: sql maxdate

需要一些帮助,这是我的SQL下面的内容:我得到了重复项,它不会返回我的LastRespondedDate字段。任何帮助将不胜感激。

SELECT t.[column1],
       pr.[column1],
       pr.[RespondedDttm],
       t.[column2],
       t.[column3],
       t.[column4]
FROM Table1 t LEFT JOIN
(
    SELECT [t.column1], [pr.column2], [RespondedDttm], MAX([RespondedDttm]) AS LastRespondedDate
    FROM Table2 pr
    GROUP BY [column1], RespondedDttm, [pr.column3]) pr
    ON (t.[column1] = pr.[column1])
WHERE t.[column8] IN (value) AND
      (pr.[RespondedDttm] >= '2015-09-01') AND
      (pr.[Response] IS NOT Null)

1 个答案:

答案 0 :(得分:0)

SELECT
    t.[column1],
    pr.[RespondedDttm] as LastRespondedDate,
    t.[column2],
    t.[column3],
    t.[column4]
FROM
    Table1 t
    LEFT JOIN
    (
       SELECT
          t2.[Column1]
          ,t2.[column2]
          ,[RespondedDttm]
          ,RowNum = ROW_NUMBER() OVER (PARTITION BY ColWithDups ORDER BY [RespondedDttm])
          ,WithTiesRowNum = RANK() OVER (PARTITION BY ORDER BY [RespondedDttm] DESC) 
       FROM
          Table2 t2
       WHERE
          t2.[RespondedDttm] >= '2015-09-01'
          AND t2.[Response] IS NOT Null
    ) pr
    ON (t.[column1] = pr.[column1])
    AND pr.RowNum = 1
    --AND pr.WithTiesRowNum = 1 --use this line if you want ties
WHERE
    t.[column8] IN (value)

如果你只想要一行,你可以使用窗口函数和ROW_NUMBER;如果你想要所有的关系,你可以使用RANK()。

如果你想要另一个细微差别的方向,我认为你评论建议:

SELECT
    t.[column1],
    pr.[RespondedDttm] as LastRespondedDate,
    t.[column2],
    t.[column3],
    t.[column4]
FROM
    Table1 t
    LEFT JOIN
    (
       SELECT
          t2.[Column1]
          ,t2.[column2]
          ,[RespondedDttm]
          ,RowNum = ROW_NUMBER() OVER (PARTITION BY ColWithDups ORDER BY [RespondedDttm])
          ,WithTiesRowNum = RANK() OVER (PARTITION BY ORDER BY [RespondedDttm] DESC) 
       FROM
          Table2 t2
    ) pr
    ON (t.[column1] = pr.[column1])
    AND pr.[RespondedDttm] >= '2015-09-01'
    AND pr.[Response] IS NOT Null
    AND pr.RowNum = 1
    --AND pr.WithTiesRowNum = 1 --use this line if you want ties
WHERE
    t.[column8] IN (value)