sql server - Getting unique records for each group using sql -
i have sql log table 2 columns this:
registrantid compnayid creation date 1 1 ..... 1 1 2 1 3 1 1 2 2 2 2 2 3 2 .....
i have stored procedure brings first record based creation date. brings 1 record if 2 companies has same registrant id registrantid 1, being first row , not 5th row, , registrantid 2, bring row 3 not 6th. want row 1 , 5 registrantid 1 , 3rd , 6th registrantid 2, row 4 , 8 registrant id 3. here stored procedure.
alter procedure [dbo].[hr_actionlog_getlist] @action int = null, @datefrom datetime = null, @dateto datetime = null, @companyid int = null, @registrantid int = null, @vacancyid int = null, @language int = 1 begin cte ( select al.*, rv.forename, rv.surname, rv.username registrantusername, e.forename employeeforename, e.surname employeesurname, u.username, case when @language = 2 c.namelang2 else c.namelang1 end companyname, case when @language = 2 v.jobtitlelang2 else v.jobtitlelang1 end jobtitle , row_number() over(partition al.registrantid order actiondate asc) rn dbo.hr_actionlog al left outer join dbo.registrantslistview rv on al.registrantid = rv.registrantid left outer join dbo.hr_employees e on al.employeeid = e.employeeid left outer join dbo.hr_users u on al.userid = u.userid left outer join dbo.hr_companies c on al.companyid = c.companyid left outer join dbo.hr_vacancies v on al.vacancyid = v.vacancyid left outer join dbo.hr_companies vc on v.companyid = vc.companyid (@action null or al.action = @action) , (@datefrom null or dbo.dateonly(al.actiondate) >= dbo.dateonly(@datefrom)) , (@dateto null or dbo.dateonly(al.actiondate) <= dbo.dateonly(@dateto)) , (@companyid null or al.companyid = @companyid) , (@registrantid null or al.registrantid = @registrantid) , (@vacancyid null or al.vacancyid = @vacancyid) --order al.actiondate desc ) select * cte rn = 1; end
please suggest how change stored procedure ?
you need partition both registrantid , companyid
row_number() over(partition al.registrantid, al.companyid order actiondate asc)
Comments
Post a Comment