2016-09-23 99 views
1

在我的學生表中我有一些學生的信息。爲什麼我的獨特功能在Oracle中不起作用?

id |phone  |name |age |sex 
---|-------------|------- |-------|------- 
1 |13553841211 |name1 |11  |1 
2 |13553841212 |name2 |12  |0 
3 |13553841213 |name3 |13  |1 
4 |13553841214 |name4 |14  |0 
5 |13553841214 |name5 |15  |1 

現在我想選擇所有的信息。如果手機的計數大於1,我只想返回一個id爲max的行。 我想要的結果:

id |phone  |name |age |sex 
---|-------------|------- |-------|------- 
1 |13553841211 |name1 |11  |1 
2 |13553841212 |name2 |12  |0 
3 |13553841213 |name3 |13  |1 
5 |13553841214 |name5 |15  |1 

我的代碼是在這裏,有什麼不對?

select name,phone,id from student where 
id in (select max(id) from student having count(phone)>=1); 


select name,distinct(phone),id from student; 
+1

之所以你的代碼不工作是因爲'不同'適用於所有列選擇列表。以你嘗試過的方式將某些列從獨特性中排除是沒有意義的。相反,您需要確定每個電話號碼具有最高ID的行,然後選擇該行。有很多方法可以做到這一點,正如您提供的解決方案所示。哪一個性能最高的數據庫和數據是由您來測試的。 – Boneist

+1

因爲'distinct'是***不是***的功能。 –

回答

6

試試這個

select * 
from 
(
select name, id, phone, age, sex, row_number() over(partition by phone order by id desc) as stu_ord 
from student 
) 
where stu_ord = 1 
0

試試這個:

SELECT name,phone,id 
FROM student s1 
WHERE NOT EXISTS 
    (SELECT 'next' 
    FROM student s3 
    WHERE s3.phone = s1.phone 
    AND s3.id > s1.id) 
1

試試這個:

SELECT t1.* 
FROM STUDENT t1 
INNER JOIN (
    SELECT MAX(ID) as ID,phone 
    FROM student 
    GROUP BY phone 
)t2 
ON t1.ID =t2.ID 
+1

Thanks.It works.It should use on t1.ID = t2.ID,not WHERE t1.ID = t2.ID – Sarly

+1

t2需要該'max(id)'的別名或該連接不起作用 – JohnHC

+1

@JohnHC是的!更新了 –

相關問題