I have a join of 5 tables to get the tasks posted by each member having about 15 columns. But for sample code I have taken just two tables of them.
SELECT TOP 5
dbo.MemberMst.MemberID, dbo.MemberMst.fname,
dbo.TaskMst.TaskMstID, dbo.TaskMst.OnDate, dbo.TaskMst.Description
FROM
dbo.MemberMst
LEFT JOIN
dbo.TaskMst ON dbo.MemberMst.MemberID = dbo.TaskMst.MemberID
Output is:
MemberID fname TaskMstID OnDate Description
3 Ursula NULL NULL NULL
84 Opeyemi 30 2012-09-18 00:00:00.000 asd
85 test 21 2012-09-18 10:30:46.900 aaa
85 test 22 2012-09-18 10:31:04.967 eeee
85 test 23 2012-09-18 10:31:26.640 vvvv
Here in above query I get 3 rows for MemberID=85
who posted 3 tasks but I need only one task from that member which is the latest. How to get the latest task posted by a member so that result would be:-
MemberID fname TaskMstID OnDate Description
3 Ursula NULL NULL NULL
84 Opeyemi 30 2012-09-18 00:00:00.000 asd
85 test 23 2012-09-18 10:31:26.640 vvvv
I mean to say just only one record for each memberID
having tasks?
Help appreciated..!
Thanks in advance...!
Since you are using SQL Server 2008, you can take advantage of Window Functions
.
Try something like this:
SELECT c.MemberID, c.fname, c.TaskMstID, c.OnDate, c.Description
FROM
(
SELECT a.MemberID, a.fname,
b.TaskMstID, b.OnDate, b.Description,
ROW_NUMBER() OVER (Partition BY a.MemberID ORDER BY b.OnDate DESC) RN
FROM MemberMst a
LEFT JOIN TaskMst b
ON a.MemberID = b.MemberID
) c
WHERE c.RN = 1
;With Cte1 AS
(
SELECT top 5 dbo.MemberMst.MemberID, dbo.MemberMst.fname, dbo.TaskMst.TaskMstID, dbo.TaskMst.OnDate, dbo.TaskMst.Description
FROM dbo.MemberMst left JOIN
dbo.TaskMst ON dbo.MemberMst.MemberID = dbo.TaskMst.MemberID
),
Cte2 As
( SELECT Rn = Row_Number() Over(Partition by MemberId Order By OnDate Desc), *
From Cte1
)
Select *
From Cte2
Where Rn = 1
Should do the task for you. Try it out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With