SQL查询从具有重复数字的列中选择第一个值

时间:2018-02-28 07:23:06

标签: sql sqlite

我想检索列中重复值的所有第一个值。 我的表格如下

ID   FirstName   LastName   sequence
1      John        Doe       1
2      Bugs        Bunny     1
3      hari        Joh       2
4      Ram        Johns      2
5      Ramaaa     Sam        3

我想要的查询将从FirstName

返回值john,hari,Ramaaa

2 个答案:

答案 0 :(得分:0)

使用GROUP BY子句与MIN()函数获取最高的名字和姓氏

SELECT 
        MIN(ID) ID,
        MIN(FirstName) FirstName,
        MIN(LastName) LastName,   
        sequence 
FROM table 
GROUP BY sequence

您还可以使用子查询方法

SELECT * 
FROM table 
WHERE ID IN (
     SELECT MIN(ID) FROM table
     GROUP BY sequence
) 

答案 1 :(得分:0)

SELECT id, firstname, lastname, seq
FROM 
( SELECT id, firstname, lastname, seq,
ROW_NUMBER() OVER (PARTITION BY seq ORDER BY seq) RANK 
FROM YOUR_TABLE ) 
WHERE RANK = 1;

SELECT * FROM YOUR_TABLE WHERE ID IN ( SELECT MIN(id) FROM YOUR_TABLE GROUP BY seq )