March 10, 2016 at 1:11 pm
Hi,
Sample data to play with
Declare @Company table(CompId int,CompanyName varchar(30));
Declare @UserVisit table (UserId int,CompId int, VisitedDate datetime);
Insert into @Company select 1, 'Microsoft' union all select 2,'IBM' union all select 3,'Oracle';
Insert into @UserVisit select 100,1,'2016-02-10' union all
select 100,1,'2016-02-01' union all
select 1000,2,'2016-01-15' union all
select 1000,2,'2016-01-10' union all
select 2000,3,'2015-12-30' union all
select 2000,3,'2012-12-04'
Expected result:
select 100 as UserId ,'Microsoft' as CompanyName,'2016-02-10' as lastvisited union all
select 1000,'IBM','2016-01-15' union all
select 1001,'Oracle','2015-12-30'
This is not my actual column name and actual table structure.I build this data to play with. Basically, i would like to know how to get the latest visited records by CompId.
Any sample query to show how to achieve this please
Thanks
March 10, 2016 at 1:22 pm
Use a CTE with ROW_NUMBER to find the first for each group.
WITH CTE AS(
SELECT c.CompanyName,
v.UserId,
v.VisitedDate,
ROW_NUMBER() OVER(PARTITION BY c.CompId ORDER BY v.VisitedDate DESC) rn
FROM @Company c
JOIN @UserVisit v ON c.CompId = v.CompId
)
SELECT UserId,
CompanyName,
VisitedDate
FROM CTE
WHERE rn = 1;
March 10, 2016 at 1:22 pm
KGJ-Dev (3/10/2016)
Hi,Sample data to play with
Declare @Company table(CompId int,CompanyName varchar(30));
Declare @UserVisit table (UserId int,CompId int, VisitedDate datetime);
Insert into @Company select 1, 'Microsoft' union all select 2,'IBM' union all select 3,'Oracle';
Insert into @UserVisit select 100,1,'2016-02-10' union all
select 100,1,'2016-02-01' union all
select 1000,2,'2016-01-15' union all
select 1000,2,'2016-01-10' union all
select 2000,3,'2015-12-30' union all
select 2000,3,'2012-12-04'
Expected result:
select 100 as UserId ,'Microsoft' as CompanyName,'2016-02-10' as lastvisited union all
select 1000,'IBM','2016-01-15' union all
select 1001,'Oracle','2015-12-30'
This is not my actual column name and actual table structure.I build this data to play with. Basically, i would like to know how to get the latest visited records by CompId.
Any sample query to show how to achieve this please
Thanks
How about this
SELECT C.UserId, C.CompanyName, MAX(U.VisitedDate) lastvisited
FROM @Company C
INNER JOIN @UserVisit U ON C.UserID = U.UserID
GROUP BY C.UserId, C.CompanyName;
March 10, 2016 at 1:52 pm
Thank you champs and i tried with cross apply to and it's working. Nice to learn three ways to achieve this. Appreciated your time.
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply