2016-07-26 73 views
1

假設我有一個表,「訂單」象下面這樣:在SQL中,選擇其計數超過給定數列的獨特元素

enter image description here

我已經進入到這個SQLfiddle(http://sqlfiddle.com/#!9/b9d7a/6)作爲如下:

CREATE TABLE Orders 
    (`Number` int, `order_date` varchar(10), `cust_id` int, `salesperson_id` int, `Amount` int) 
; 

INSERT INTO Orders 
    (`Number`, `order_date`, `cust_id`, `salesperson_id`, `Amount`) 
VALUES 
    (10, '8/2/96', 4, 2, 540), 
    (20, '1/30/99', 4, 8, 1800), 
    (30, '7/14/95', 9, 1, 460), 
    (40, '1/29/98', 7, 2, 2400), 
    (50, '2/3/98', 6, 7, 600), 
    (60, '3/2/98', 6, 7, 720), 
    (70, '5/6/98', 9, 7, 150) 
; 

我想選擇哪個出現一次以上的salesperson_id的元素。到現在我已經做了

SELECT 
    salesperson_id 
FROM 
    Orders 
GROUP by salesperson_id 

但是這將導致選擇的salesperson_id所有獨特的元素 - 也就是說,127,並8 - 而不是僅僅發生一次以上的那些,即,27。有什麼辦法可以做GROUP by指定最小計數值?

回答

3
SELECT salesperson_id, count(salesperson_id) as c 
FROM Orders 
GROUP by salesperson_id 
HAVING c>1 

,甚至更短的

SELECT salesperson_id FROM Orders GROUP by salesperson_id HAVING count(salesperson_id)>1