sql 重复的数据取第一条记录的ID,如何写这样的sql?
例:
ID CUSTOMER PRODUCTNUMBER
001 C01 P00001
002 C01 P00001
003 C02 P00002
004 C02 P00002
--------------------------------
结果:
ID CUSTOMER PRODUCTNUMBER
001 C01 P00001
003 C02 P00002
[解决办法]
declare @t table (ID varchar(3),CUSTOMER varchar(3),PRODUCTNUMBER varchar(6))insert into @tselect '001','C01','P00001' union allselect '002','C01','P00001' union allselect '003','C02','P00002' union allselect '004','C02','P00002'select * from @t t whereID =(select min(ID) from @t where PRODUCTNUMBER=t.PRODUCTNUMBER)/*ID CUSTOMER PRODUCTNUMBER---- -------- -------------001 C01 P00001003 C02 P00002*/
[解决办法]
select * from tb t where not exists(select 1 from tbwhere CUSTOMER=t.CUSTOMER and PRODUCTNUMBER=t.PRODUCTNUMBER and id<t.id)
[解决办法]
select *from tb twhere not exists (select 1 from tb where customer = t.customer and id > t.id)
[解决办法]
+1
select *from tb twhere not exists (select 1 from tb where customer = t.customer and id > t.id) and exists (select 1 from tb where customer = t.customer and id <> t.id)
[解决办法]
use tempdb;/*create table A( ID nvarchar(10) not null, CUSTOMER nvarchar(10) not null, PRODUCTNUMBER nvarchar(10) not null);insert into A values('001','C01','P00001'),('002','C01','P00001'),('003','C02','P00002'),('004','C02','P00002'),('005','C03','P00003'),('006','C04','P00004');*/select B.ID,B.CUSTOMER,B.PRODUCTNUMBERfrom( select *,row_number() over(partition by A.CUSTOMER,A.PRODUCTNUMBER order by A.ID desc) as [orderno] from A) as Bwhere B.[orderno] = 1;
[解决办法]
declare @t table (ID varchar(3),CUSTOMER varchar(3),PRODUCTNUMBER varchar(6))insert into @tselect '001','C01','P00001' union allselect '002','C01','P00001' union allselect '003','C02','P00002' union allselect '004','C02','P00002' union allselect '005','C03','P00003' union allselect '006','C04','P00004'SELECT MIN(ID) FROM @T GROUP BY PRODUCTNUMBER HAVING COUNT(1)>1