2

我是 sql 新手,遇到了一个小问题。我有一个这样的查询:

select cust_id, count(1) from all_customers
group by cust_id
having count(1)>4;

该查询给了我想要的结果。

我需要对all_customers表中的所有客户进行新查询,并排除我刚刚从上面的查询中得到的结果。我试着做这样的事情:

select * from all_customers
where cust_id NOT IN 
(
    select cust_id, count(1) from all_customers
    group by cust_id
    having count(1)>4
)

但我收到错误消息too many values。我究竟做错了什么?

4

2 回答 2

6

您应该摆脱子句中的聚合列。NOT IN原因是您只比较cust_id列。另请注意,使用 时NOT IN,子查询应始终返回单列。

select * 
from all_customers
where cust_id NOT IN 
      (
         select cust_id 
         from all_customers
         group by cust_id
         having count(1)>4
      )
于 2012-09-26T13:57:35.660 回答
1

子查询中有很多列,请尝试:

select * from all_customers
where cust_id NOT IN 
(select cust_id
 from all_customers
 group by cust_id
 having count(1)>4)
于 2012-09-26T13:58:24.990 回答