从count(*)查询中减去字段的值

时间:2015-10-21 06:58:31

标签: sql sql-server

我有三张桌子:

  1. Plans(PlanID(key), Capacity)
  2. CustomerInProject(VahedID, cinpid(key))
  3. Vahed(VahedID(key), PlanID,...)
  4. 此查询显示人们雇佣的具有相同PlanID(地图)的房屋数量:

    select 
        count(*) 
    from
        Vahed as v2,
        CustomerInProject 
    where 
        CustomerInProject.VahedID = v2.VahedID
    group by PlanID 
    

    Plans有一个名为int的{​​{1}}字段。我想从上面的查询中减去Capacity。我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

这样的事情应该这样做:

select p.PlanID, count(*) - p.Capacity
from Vahed as v2
join CustomerInProject c
  on c.VahedID = v2.VahedID
join Plan p
  on p.PlanID = c.PlanID /* or v.PlanID, it's not clear from the question */
group by p.PlanID, p.Capacity

在第6行,您可能希望将c.PlanID替换为v.PlanID - 我不知道确切的表格架构。

答案 1 :(得分:0)

    select sum(cnt)
    from
    (select capacity*-1  as cnt from
    plans
    union 
    select count(*)  as cnt from Vahed as v2
inner join 
      CustomerInProject  on 
        CustomerInProject.VahedID = v2.VahedID
         group by PlanID )