減值

2015-10-21 51 views
0

我有三個表:減值

  1. Plans(PlanID(key), Capacity)
  2. CustomerInProject(VahedID, cinpid(key))
  3. Vahed(VahedID(key), PlanID,...)

此查詢顯示房子有相同數量的PlanID(地圖)那個人僱用的:

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

Plans有一個int字段名爲Capacity。我想從上面的查詢中減去Capacity。我怎樣才能做到這一點?

+3

[避免使用舊式'JOIN'語法(http://sqlblog.com/blogs/aaron_bertrand/archive/2009/10/08/bad-habits-to-kick-using-old- style-joins.aspx) –

+1

你可以發佈三個表的表結構嗎?只包括相關的欄目。 –

回答

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 

六號線,你可能需要更換c.PlanIDv.PlanID - 我不知道確切的表模式。

+2

錯字,刪除「在哪裏」。 – jarlh

+0

@jarlh好了,謝謝! – GolfWolf

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)