从两个不相关的表中减去列数据

时间:2018-12-16 09:30:57

标签: sql sql-server

snapshot of the database diagram

  

这是我要确定通过从[Amount Accepted]中减去[Amount Donated]来获得的每个库中剩余血液的数据库图

     

我试图选择抽取到银行中的血液和从银行中抽取的血液,但是我的问题是我不能减去两列[blood drawn][blood withdrawn],因为它们不在表格中相关

snapshot of the selections

3 个答案:

答案 0 :(得分:2)

您可以尝试以下操作。

foo()

答案 1 :(得分:0)

将派生表或公用表表达式中的所有选择都包装起来,然后将它们联接起来,例如

with donated as
 ( select ...
 )
, accepted as
 ( select ...
 )
select ...
from donated as a
join accepted as a 
  on a.[blood bank name] = d..[blood bank name]

答案 2 :(得分:0)

请注意,[Amount Accepted]之前的'-'是键。

SELECT x.[Blood Bank Name], SUM(x.[Net Amount])
FROM 
(
    SELECT [Blood Bank Name],  [Amount Donated] AS [Net Amount] 
    FROM [Donation Record]
    UNION ALL
    SELECT [Blood Bank Name], -[Amount Accepted] AS [Net Amount] 
    FROM [Transfusion Record]        
) x
GROUP BY x.[Blood Bank Name]