在SQL中,选择计数超过给定数量的列的唯一元素

时间:2016-07-26 17:28:50

标签: mysql

假设我有一张桌子"订单"如下所示:

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的所有独特元素 - 即1278 - 而不是只是出现不止一次的那些,即27。有什么方法可以GROUP by指定最小计数?

1 个答案:

答案 0 :(得分: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