假设我有一张桌子"订单"如下所示:
我已将此输入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
的所有独特元素 - 即1
,2
,7
和8
- 而不是只是出现不止一次的那些,即2
和7
。有什么方法可以GROUP by
指定最小计数?
答案 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