How to select rows with same Id but different value in SQL Server
By FoxLearn 5/15/2024 4:02:02 AM 773
I spent hours and read many articles to find a way to solve the above problem.
If you need to get a list of "duplicate" rows where the StudentId is the same value but they have a different value in a Number column.
Id | StudentId | Number
1 | 1054 | 111112
2 | 1054 | 111112
3 | 1054 | 111123
4 | 1061 | 232321
5 | 1061 | 232321
The query based on the above should return 1054, 1061
Id | StudentId | Number
1 | 1054 | 111112
3 | 1054 | 111123
4 | 1061 | 232321
How to select rows with same Id but different value in SQL Server
To select rows with the same Id
but different values in another column in SQL Server, you can use a query with a subquery, or the PARTITION
clauses.
Following is an idea how can i achieve this in SQL
select Id, StudentId, Number from ( select *, ROW_NUMBER() OVER (PARTITION BY StudentId ORDER BY Id ASC) as n from tablename) x where n = 1
You can create a partition column using StudentId which will repeat the row_number for every same value of Number column.
Finally, you need to eliminate duplicate records using where condition n = 1
- How to fix 'The transaction log for the database is null due to OLDEST_PAGE'
- How to convert varchar to uniqueidentifier in SQL Server
- How to convert timestamp to date in SQL Server
- How to Download and Restore Northwind database to SQL Server
- How to Download Microsoft SQL Server
- Saving changes is not permitted in SQL Server
- How to change ‘Edit Top 200 Rows’ and ‘Select Top 1000 Rows’ in SQL
- How to fix 'The specified sa password does not meet strong password requirements'