如何选择在表格中出现多次的记录

时间:2012-05-24 10:57:40

标签: sql

我有一张这样的桌子:

book_no     lang      price      shelf     
----------  --------  ---------  -----
1           eng       20         a  
4           french    34         a  
2           eng       26         b  
7           russian   71         b  
12          german    33         a  
43          french    15         d  
11          eng       43         c  
14          rusian    33         a  
19          eng       20         d  
24          french    40         c  
23          eng       57         a  
27          russian   48         b  
42          german    31         c  
25          french    15         d  

从这张表中我想获取book_no,语言,架子 出现的语言超过3次,只显示那些书籍 我试过了:

select book_no,lang,shelf from a where (count(lang)>3)    

提前感谢您的帮助

3 个答案:

答案 0 :(得分:4)

SELECT book_no, 
       lang, 
       shelf 
FROM   a 
WHERE  lang IN (SELECT lang 
                FROM   A 
                GROUP  BY lang 
                HAVING Count(*) > 3) 

答案 1 :(得分:1)

像count,sum这样的组函数不能在where子句中使用。

使用

group by book_no -- or the fields you need, depending on sgbd, you can put one or have to put all

和有条款

Having count(lang) > 3

答案 2 :(得分:0)

如果您的DBMS支持聚合窗口函数,您可以尝试这样做:

SELECT
  book_no,
  lang,
  shelf
FROM (
  SELECT
    *,
    COUNT(*) OVER (PARTITION BY lang) AS book_count
  FROM a
) s
WHERE book_count >= 3