SQL Query显示基于最小值+非重复的行

时间:2017-08-25 08:26:10

标签: mysql sql

你能帮忙解决这个noob查询吗?

每个" s"只需要首先显示" t"(min" id")每个" c":

id  |c   | s  | t   
--- |--- |--- |---  
1   | C1 | S1 | TA  
2   | C1 | S1 | TA  
3   | C1 | S1 | TB  
4   | C2 | S3 | TA  
5   | C2 | S3 | TC  
6   | C1 | S2 | TC  
7   | C9 | S2 | TF  
8   | C9 | S4 | TA  
9   | C8 | S2 | TB  

因此,在给定的示例中,最终结果将是:

id  |c   | s  | t   
--- |--- |--- |---  
1   | C1 | S1 | TA  
4   | C2 | S3 | TA
6   | C1 | S2 | TC  
7   | C9 | S2 | TF  
8   | C9 | S4 | TA  
9   | C8 | S2 | TB  

编辑:尝试在MySQL 5.7中执行此操作 谢谢!

3 个答案:

答案 0 :(得分:0)

SQL server,oracle和Postgres:

with CTE as
(
select t1.*, 
       row_number() over(partition by c,s order by id) rn
from t1
)
select t1.*
from CTE
where rn = 1

MySQL的

select t1.*
from t1
inner join 
(
select c,s,min(id) as minid
from t1
group by c,s
) x2
on --x2.c = t1.c -- oops, don't need these
--and x2.s = t1.s
--and 
x2.minid = t1.id

答案 1 :(得分:0)

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,c CHAR(2) NOT NULL
,s CHAR(2) NOT NULL
,t CHAR(2) NOT NULL
);

INSERT INTO my_table VALUES
(1,'C1','S1','TA'),
(2,'C1','S1','TA'),
(3,'C1','S1','TB'),
(4,'C2','S3','TA'),
(5,'C2','S3','TC'),
(6,'C1','S2','TC'),
(7,'C9','S2','TF'),
(8,'C9','S4','TA'),
(9,'C8','S2','TB');  


SELECT a.* 
  FROM my_table a 
  JOIN 
     ( SELECT MIN(id) id FROM my_table GROUP BY c,s ) b 
    ON b.id = a.id;
+----+----+----+----+
| id | c  | s  | t  |
+----+----+----+----+
|  1 | C1 | S1 | TA |
|  6 | C1 | S2 | TC |
|  4 | C2 | S3 | TA |
|  9 | C8 | S2 | TB |
|  7 | C9 | S2 | TF |
|  8 | C9 | S4 | TA |
+----+----+----+----+

答案 2 :(得分:0)

.DS_Store
nbproject/private/
app/tmp/cache/models/
app/tmp/cache/persistent/
app/tmp/cache/views/
app/tmp/logs/

此查询适用于MySQL。