2009-09-15 132 views
16

我有一個表programparticipants。我目前正在成功查詢ID爲count(name) > 1。我現在需要的是查詢屬於這些ID的名稱,其中count(name) > 1SQL查詢需要獲取名稱,其中count(id)= 2

導致例如目前正在返回的數據:

ID  count(name) 
1  2 
3  4 
4  3 

例,結果所需要的數據:

ID  name 
1  nm1 
1  nm3 
3  nm2 
3  nm3 
3  nm4 
3  nm7 
4  nm5 
4  nm8 
4  nm9 

回答

6

您可以使用此:

SELECT 
    (SELECT name FROM participants WHERE id=p.participantid) AS name 
FROM 
    programparticipants AS p 
WHERE 
    .... (the part where you find count(name)>1) 
+0

這是通過使用每個人的建議和拼湊在一起 – mattgcon 2009-10-28 17:14:46

2
select id, Name 
from programparticipants 
where id in (<your current query selecting only id here>) 
+0

'<你當前的查詢只選擇ID而不是COUNT(*)here>'? – 2009-09-15 22:24:19

+0

嗯...是的。修復... – 2009-09-15 22:50:41

51
select count(id), name 
from programparticipants 
group by name 
having count(id) > 1 
+1

恕我直言,這應該是正確的答案。有點晚了,但嘿... – seebiscuit 2015-02-11 01:00:55

4

我認爲GROUP BY and HAVING是你想要的。

+0

是的,一些組合,並具有肯定是他所需要的。問題中沒有足夠的細節來編寫整個查詢。 – 2009-09-15 22:26:22

+0

我甚至沒有嘗試過。這條鏈接是我能夠迅速提出的最好的鏈接。 – duffymo 2009-09-15 22:42:34

1

想想你會想看看組通過與具有:

select id, name, count(name) from table group by 2,1 having count(name) = 2; 

您可以替換= 2> 1,具體取決於任何你想要的(標題所說= 2,問題說> 1)

1
SELECT id, Name 
FROM programparticipants 
GROUP BY id, Name 
HAVING COUNT(*) > 1