2011-05-23 94 views
19

我需要查詢我的數據庫,以顯示我的表內的姓氏出現三次以上的姓氏。例如:在我的學生表中,有3個姓'Smith',4個'Johnson',1個'Potter'。我的查詢應該顯示那些姓氏史密斯和約翰遜的記錄,因爲這些值的出現次數大於或等於3次。SQL查詢獲取值不止一次

任何人都可以指向我嗎?我正在考慮使用COUNT(),但似乎無法考慮如何應用它?

+0

什麼RDBMS好嗎? – 2011-05-23 09:57:50

回答

20

對於SQL Server 2005+

;WITH T AS 
(
SELECT *, 
     COUNT(*) OVER (PARTITION BY Lastname) as Cnt 
FROM Students 
) 
SELECT * /*TODO: Add column list. Don't use "*"     */ 
FROM T 
WHERE Cnt >= 3 
+0

五年過去了,仍然是一件藝術品。 +1 – EvilDr 2016-07-28 09:31:34

4
SELECT LASTNAME, COUNT(*) 
FROM STUDENTS 
GROUP BY LASTNAME 
ORDER BY COUNT(*) DESC 
+1

OP要求「史密斯和約翰遜姓氏的記錄」不僅僅是姓氏本身。 – 2011-05-23 10:09:29

9

對於MySQL:

SELECT lastname AS ln 
    FROM 
    (SELECT lastname, count(*) as Counter 
    FROM `students` 
    GROUP BY `lastname`) AS tbl WHERE Counter > 2 
13

從甲骨文(但在大多數SQL的DB 工作):

SELECT LASTNAME, COUNT(*) 
FROM STUDENTS 
GROUP BY LASTNAME 
HAVING COUNT(*) >= 3 

附:這是更快一個,因爲你沒有選擇withing選擇方法這裏

0

對於PostgreSQL:

SELECT * AS rec 
FROM (
    SELECT lastname, COUNT(*) AS counter 
    FROM students 
    GROUP BY lastname) AS tbl 
WHERE counter > 1; 
2

這裏所說的回答也相當考究https://stackoverflow.com/a/6095776/1869562但在測試時,我意識到它只返回姓氏。 如果您想要返回整個記錄本身,該怎麼辦? 做到這一點 (MySQL的)

SELECT * 
FROM `beneficiary` 
WHERE `lastname` 
IN (

    SELECT `lastname` 
    FROM `beneficiary` 
    GROUP BY `lastname` 
    HAVING COUNT(`lastname`) >1 
) 
+0

很好,謝謝! – Hammerbot 2017-06-13 10:42:53