我正在使用SQL Server 2008
我有2个表,我希望从第1个表中获得2列,从第2个表中获得1个列
当我做JOIN时,它给了我另一件事......
这是我的代码:
Select SUM(Sales.CDnum) as CDnum, SUM(Sales.Total) as TotalMoney,
SUM(Expenses.Costs) as Expenses, SUM(Sales.Total - Expenses.Costs) as Winnings
from Sales
JOIN Expenses
ON Sales.ID = Expenses.ID
但是当我执行代码时,它只给我第一张表中的一个原始和第二张中的1个原始...因为我在第二张表中有1个原始而第一个我有很多原始...
有人可以帮助我....答案 0 :(得分:0)
因为我看到ID列在两个表中都没有相互关联,所以你需要将它们联合起来,例如在这个查询中:
select sum(q.sales), sum(q.expense), sum(q.sales)-sum(q.expense) as winnings
from (
select sum(Sales.Total) as sales, 0 as expense from Sales
union all
select 0 as sales, sum(Expenses.Costs) as expense from Expenses
) as q