在SQL Server中分组并具有OR条件

时间:2015-09-17 20:20:46

标签: sql sql-server sql-server-2008

注意(deptid = 2,3)或(deptid = 1且总和(总费用)= 0)

select * 
into employee1 
from employee2 
where empid in (select distinct empid 
                from employee3 e3 
                join employee2 e2 on e3.empid = e2.empid
                where e3.deptid in (2,3) 
                   or (e3.deptid = 1 
                group by empid, cost  
                having sum(e2.cost) = 0))

1 个答案:

答案 0 :(得分:0)

我会给你一个很大的猜测。这些都是我的问题。

  1. 该查询可能会返回多个结果,因此无法使用INTO employee1
  2. employee3看起来应该是depatment table
  3. 我创建了一个cte来首先计算每个员工的成本。然后验证部门。

    WITH ecost as (
        select e.empid, SUM(e.cost) as cost
        from employee2 e
        group by e.empid
    )
    select e.empid
    from ecost e
    inner join employee3 d
           on e.empid = d.empid           
    where 
       d.deptid  in (2,3)
    or (d.deptid = 1 and e.cost = 0)