根据一列

时间:2017-12-11 13:21:01

标签: mysql sql

我想根据公司ID消除重复。 我不在乎模型名称下的哪些记录会被删除/保留。

我有这样的结果:

+------------+------------------+
| company id | model name       |
+------------+------------------+
|    1       | chevrolet camaro |
|    1       | chevrolet spark  |
|    1       | chevrolet cruze  |
|    2       | mercedes c class |
|    2       | mercedes E class |
+------------+------------------+

我想得到这些结果:

+------------+------------------+
| company id | model name       |
+------------+------------------+
|    1       | chevrolet camaro |
|    2       | mercedes c class |
+------------+------------------+

或者这些结果(重点是我不关心哪个型号名称将被淘汰):

+------------+------------------+
| company id | model name       |
+------------+------------------+
|    1       | chevrolet spark  |
|    2       | mercedes E class |
+------------+------------------+

我该怎么办?

3 个答案:

答案 0 :(得分:2)

您可以使用group by

select companyid, min(modelname) as modelname
from t
group b companyid;

答案 1 :(得分:0)

试试这个

ALTER IGNORE TABLE 'yourTableName' ADD UNIQUE ('company id');

参考:here

答案 2 :(得分:0)

我会尝试这种方法:

declare @tbl table (ID int, car nvarchar(100))
declare @tblTemp table (ID int, car nvarchar(100))
insert into @tbl(ID, car)
values
( 1 ,'chevrolet camaro'),
(1 ,'chevrolet spark'),  
(1 ,'chevrolet cruze'),  
(2 ,'mercedes c class'), 
(2 ,'mercedes E class'), 
(1 ,'chevrolet camaro'),
(1 ,'chevrolet spark'),  
(1 ,'chevrolet cruze'),  
(2 ,'mercedes c class'), 
(2 ,'mercedes E class')

insert into @tblTemp
select distinct  MAX(id), car from @tbl
group by car

delete from @tbl


insert into @tbl (car)
select car from @tblTemp

declare @i int  
  SELECT @i= ISNULL(MAX(id),0)  FROM @tbl


update @tbl
set id  = @i , @i = @i + 1
where id is null
select * from @tbl

SQL结果: enter image description here