Friends often ask questions similar to this.
The data in the table is as follows
ID AA BB
1 123 456
1 4535 54
1 60 6564
1 60 656
2 50 664
2 60 6
3 89 89
4 40 4242
The desired result is
ID AA BB
1 123 456
2 50 664
3 89 89
4 40 4242
Of course, the environment is SQL Server
The answers and analysis are as follows:
1. Many friends hope to use distinct to solve the problem, but it is impossible, distinctivect Ignore duplicate records,
but it ignores identical duplicate records, not records in which a certain field is repeated, so there is only syntax like
select distinct ID,AA,BB from tName
Other writing methods such as select distinct(ID),AA,BB from tName or
select ID,distinct AA,BB are invalid
2, use group by and aggregate function
select ID ,MAX(AA) AS AA,MAX(BB) AS BB from tName group by ID
The following results can be obtained
ID AA BB
1 4535 6564
2 60 664
3 89 89
4 40 4242
The ID is unique, but the subsequent fields may not be the same record
3, use the temporary table
select IDENTITY(INT,1,1) as TID,ID, AA,BB into #Tmp from tName
select t1.ID,t1.AA,t1.BB from #Tmp t1 where t1.TID in
(select min(T2.TID) from #Tmp t2 group by t2 .ID)
This can get results that meet the requirements
But it uses two T-SQL statements,
And if it is a large amount of data, the performance problem will be prominent
So far, I I haven’t found a way to use a T-SQL statement to achieve the same function.
If anyone has one, I hope to add