我们有一个这样的表:
id date code
-----------------------
1 01/10/14 COO1
2 02/10/14 C002
3 03/10/14 C004
1 04/10/14 C001
2 05/10/14 C002
3 06/10/14 C004
3 07/10/14 C005
所需的输出应该是这样的:
id date code
-----------------------
1 01/10/14 COO1
2 02/10/14 C002
3 03/10/14 C004
3 07/10/14 C005
我不想选择表格之前是否存在id和代码。
尝试了这个基本的SQL:
SELECT DISTINCT id
FROM mytable
但这对我无能为力
我该怎么做?
感谢帮助
答案 0 :(得分:0)
好像你按照ID和代码进行分组:
SELECT id, MIN([date]), code
FROM my_table
GROUP BY id, code
答案 1 :(得分:0)
SELECT id, MIN([date]), code
FROM my_table
GROUP BY id, code
ORDER BY id, code
答案 2 :(得分:0)
我使用了子查询,它为每个代码返回min(date)
/*CREATE TABLE tbl(
id int ,
date varchar(10),
code varchar(10))
INSERT INTO tbl (id , date , code)
VALUES
(1 , '01/10/14' , 'COO1'),
(2 , '02/10/14' , 'C002'),
(3 , '03/10/14' , 'C004'),
(1 , '04/10/14' , 'C001'),
(2 , '05/10/14' , 'C002'),
(3 , '06/10/14' , 'C004'),
(3 , '07/10/14' , 'C005')*/
SELECT DISTINCT id ,
(SELECT t.date
from (SELECT code, min(date) date
FROM tbl
WHERE code =x.code
GROUP by code) t) date,
code
FROM tbl x