[英]SQL Query to get 1 latest record per member based on a latest date
我有一个像这样的数据库:
---------------------------------------------------
| 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 |
---------------------------------------------------
现在基于CreatedDate
和instCode
,我需要一个查询,该查询基于instCode
作为参数返回如下结果。
当@IntrCode = 1
,我只需要最新的( CreatedDate
)活动的MemberID
。
PS:请注意,成员7在检查最新日期(CreatedDate)时被取消。
输出量
---------------------------------------------------
| MemberID | IntrCode | InstruReply | CreatedDate |
---------------------------------------------------
| 6 | 1 | Activated | 26 FEB 2014 |
---------------------------------------------------
我写了下面的查询,但无法显示其他列。(感谢您的帮助)
SELECT MemberID, MAX(CreatedDate) AS LatestDate FROM MyTable GROUP BY MemberID
您可以使用CTE
和ROW_NUMBER
函数 :
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
尝试这个
方法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
输出量
---------------------------------------------------
| MemberID | IntrCode | InstruReply | CreatedDate |
---------------------------------------------------
| 6 | 1 | Activated | 26 FEB 2014 |
---------------------------------------------------
这样,您可以为每个成员选择具有最新日期的整行。
SELECT * FROM MyTable t1
WHERE NOT EXISTS (SELECT *
FROM MyTable t2
WHERE t2.CreatedDate > t1.CreatedDate
AND t1.MemberID = t2.MemberID)
AND IntrCode = @IntrCode
;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
您编写的查询只是缺少WHERE
子句,它将帮助您过滤所需的数据:
SELECT MemberID, MAX(CreatedDate) AS LatestDate
FROM MyTable
WHERE IntrCode = @IntrCode
AND InstruReply = 'Activated'
GROUP BY MemberID
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.