Sql选择从同一个表中选择不起作用的地方

时间:2016-03-16 15:52:22

标签: sql sybase

我正在尝试在sybase数据库上运行sql。

首先,我想找到费用总和超过50美元的所有用户。用户可以拥有多个产品,因此我只需要花费超过50美元的用户就能看到用户。

我想我需要2个select语句,我尝试运行它,但它不能正常工作

Select usercode, name, dept, product, cost 
from table1 
where usercode = (select usercode 
                  where product = 'Apple' or product = 'orange' 
                  group by usercode 
                  having (sum(cost) > 50) ) 

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

您必须使用IN运算符:

Select usercode, name, dept 
from table1 
where usercode IN (select usercode
                   from products 
                   where product IN ('Apple', 'Orange')
                   group by usercode 
                   having sum(cost) > 50 )

或者,您可以使用JOIN

select t1.usercode, t1.name, t1.dept, t2.sum_of_cost
from table1 as t1
join (select usercode, sum(cost) as sum_of_cost
      from products 
      where product IN ('Apple', 'Orange')
      group by usercode 
      having sum(cost) > 50 
) as t2 on t1.usercode = t2.usercode

请注意,这些查询仅会检查 'Apple', 'Orange'产品的费用。