首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

sql 重复的数据取第一条记录的ID,怎么写这样的sql

2012-04-05 
sql 重复的数据取第一条记录的ID,如何写这样的sql?例:IDCUSTOMERPRODUCTNUMBER001C01P00001002C01P0000100

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

[解决办法]

SQL code
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*/
[解决办法]
SQL code
select * from tb t where not exists(select 1 from tbwhere CUSTOMER=t.CUSTOMER and PRODUCTNUMBER=t.PRODUCTNUMBER and id<t.id)
[解决办法]
SQL code
select *from tb twhere not exists (select 1 from tb where customer = t.customer and id > t.id)
[解决办法]
+1
探讨
SQL code

select *
from tb t
where not exists (select 1 from tb where customer = t.customer and id > t.id)

[解决办法]
探讨
ID CUSTOMER PRODUCTNUMBER
001 C01 P00001
002 C01 P00001
003 C02 P00002
004 C02 P00002
005 C03 P00003
006 C04 P00004
-------------------------
结果:
ID CUSTOMER PRODUCTNUMBER
001 C01 P00001
……

[解决办法]
SQL code
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)
[解决办法]
SQL code
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;
[解决办法]
SQL code
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 

热点排行
Bad Request.