SQL Query根据最新日期获得每个成员的1条最新记录

时间:2014-03-07 08:54:55

标签: sql sql-server

我有一个像这样的数据库:

---------------------------------------------------
| MemberID | IntrCode | InstruReply | CreatedDate |  ...other 2 more columns
---------------------------------------------------
| 6        | 1        | Activated   | 26 FEB 2014 |
| 7        | 2        | Cancelled   | 25 FEB 2014 |
| 6        | 2        | Cancelled   | 15 FEB 2014 |
| 7        | 1        | Activated   | 03 FEB 2014 |
---------------------------------------------------

现在基于CreatedDateinstCode,我需要一个基于instCode作为参数返回结果的查询。

@IntrCode = 1时,我只需要在最新的MemberID)上有效CreatedDate

PS:请注意在查看最新版本(CreatedDate)时会员7被取消。

输出

---------------------------------------------------
| MemberID | IntrCode | InstruReply | CreatedDate |
---------------------------------------------------
| 6        | 1        | Activated   | 26 FEB 2014 |
---------------------------------------------------

我写了下面的查询,我不能显示其他列。(我感谢你的帮助)

SELECT MemberID, MAX(CreatedDate) AS LatestDate FROM MyTable GROUP BY MemberID

5 个答案:

答案 0 :(得分:3)

您可以使用CTEROW_NUMBER function

With CTE As
(
    SELECT t.*, 
           RN = ROW_NUMBER()OVER(PARTITION BY MemberID Order By CreatedDate DESC)
    FROM MyTable t
    WHERE IntrCode = @IntrCode
)
SELECT MemberID, IntrCode, InstruReply, CreatedDate
FROM CTE
WHERE RN = 1

DEMO

答案 1 :(得分:2)

试试这个

方法1:

SELECT * FROM
(
  SELECT *,ROW_NUMBER()OVER(PARTITION BY MemberID Order By CreatedDate DESC) RN
  FROM MyTable WHERE InstruReply = 'Activated' AND IntrCode = @IntrCode
) AS T
WHERE RN = 1

方法2:

 SELECT * FROM
 (
   Select MemberID,max(CreatedDate) as LatestDate from MyTable group by MemberID
 ) As s INNER Join MyTable T ON T.MemberID = S.MemberID AND T.CreatedDate = s.LatestDate
 WHere T.InstruReply = 'Activated' T.IntrCode = @IntrCode

Fiddle Demo

输出

---------------------------------------------------
| MemberID | IntrCode | InstruReply | CreatedDate |
---------------------------------------------------
| 6        | 1        | Activated   | 26 FEB 2014 |
---------------------------------------------------

答案 2 :(得分:1)

这样,您可以为每个成员选择具有最新日期的整行。

SELECT * FROM MyTable t1
WHERE NOT EXISTS (SELECT * 
                  FROM MyTable t2 
                  WHERE t2.CreatedDate > t1.CreatedDate
                  AND t1.MemberID = t2.MemberID)
AND IntrCode = @IntrCode

答案 3 :(得分:1)

;with TempData as (Select MemberId, IntrCode   ,InstruReply,CreatedDate  , MemberCount =ROW_NUMBER()
                over(PARTITION By MemberId Order By CreatedDate desc)
                From MyTable 
                )

Select *
From TempData
Where MemberCount =1

答案 4 :(得分:1)

您编写的查询只是缺少一个WHERE子句,它可以帮助您过滤所需的数据:

SELECT MemberID, MAX(CreatedDate) AS LatestDate
FROM MyTable
WHERE IntrCode = @IntrCode
  AND InstruReply = 'Activated'
GROUP BY MemberID