Click here to Skip to main content
15,567,466 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Experts,

I have data related to Employees Branch change log in one of the table as following.


UniqueID  UID  Branch_Id Created_On    Created_By
   18791   173 31  2-Jul-2020  939
   18411   173 31  15-May-2020 5047
   17867   173 31  23-Mar-2020 939
   14614   173 27  25-Jul-2019 4165
   12958   173 27  11-May-2019 4065
   11783   173 27  7-Mar-2019  939
   11780   173 27  7-Mar-2019  939
   9719    173 27  14-Nov-2018 939
   9304    173 27  18-Oct-2018 939
   9103    173 27  9-Oct-2018  939
   7958    173 27  17-Sep-2018 939
   4549    173 27  15-Mar-2018 939
   3272    173 27  9-Jan-2018  939
   2844    173 20  6-Dec-2017  939
   2481    173 20  8-Nov-2017  939
   58           173    27  4-Jul-2013  1


The branch name/Id changes multiple times as above

I need to display the above data as following.

UniqueId  UID	 Branch_Id  Created_On	   Created_By
    17867	  173	  31	    23-Mar-2020	     939
    3272	  173	  27	    9-Jan-2018	      939
    2481	  173	  20	    8-Nov-2017	      939
    58	          173	  27	    4-Jul-2013	      1


Please guide me how can i achieve this?

Thank you.


What I have tried:

Please guide me how can i achieve this?
Posted
Updated 22-Sep-20 4:24am
v3

It looks like you want to return the full row for the earliest record for each branch.

Based on that assumption you can use GROUP BY to group up all rows for each branch, and Min to extract the UniqueId for the earliest row for each group. You can then use that list of UniqueIds to filter the original set of rows.

Assuming your table is called LogTable:

SQL
SELECT *
FROM LogTable
INNER JOIN (SELECT Min(UniqueId) as MinUniqueId
    FROM LogTable
    GROUP BY Branch_Id) AS Filtered
    ON LogTable.UniqueId = Filtered.MinUniqueId
 
Share this answer
 
Comments
Maciej Los 22-Sep-20 9:28am    
5ed!
Vikram Singh Rathaur 23-Sep-20 1:20am    
Hi Adambl, RecordId 3272 missing from branch log. It happend because you are using Group By Clause
There is nothing obvious in that data which allows just those four rows to be selected: you will have to work out what your rules are pretty carefully before you even start to design an SQL query.

When you have, you may find either GROUP BY or LEAD/LAG useful. But not until!
 
Share this answer
 
Comments
Sincobile Nhlengethwa 22-Sep-20 10:29am    
What are you comparing, which fields you want to use to compere,is it in each branch or something else?
Vikram Singh Rathaur 23-Sep-20 1:18am    
compare previous branch to next branch. Actually i want to generate branch change log

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900