我想获得所有市场的总利润。这是购买的总价格 - 您为员工支付的工资总数。
所以我有这样的疑问: 我得到每个市场的所有购买总和
SELECT
Markets.Title,
SUM(Purchase.TotalPrice) sum
FROM Purchase
INNER JOIN Employees ON Purchase.Employee_ID = Employees.Employee_ID
INNER JOIN Markets ON Employees.Market_ID = Markets.Market_ID
GROUP BY Markets.Title
在另一个查询中,我获得了工资支付市场总额:
SELECT
Markets.Title,
SUM(Employees.Salary) sum
FROM Employees
INNER JOIN Markets ON Employees.Market_ID = Markets.Market_ID
GROUP BY Markets.Title
但我很困惑如何结合这些查询以获得每个市场的利润(所有订单的总和 - 所有工资的总和)。 任何人都可以帮助我吗?
答案 0 :(得分:1)
SELECT
m.Title
, e.TotalSalary
, e.TotalPrice
FROM dbo.Markets m
JOIN (
SELECT
e.Market_ID
, TotalSalary = SUM(e.Salary)
, TotalPrice = SUM(p.TotalPrice)
FROM dbo.Employees e
JOIN (
SELECT Employee_ID, TotalPrice = SUM(TotalPrice)
FROM dbo.Purchase
GROUP BY Employee_ID
) p ON p.Employee_ID = e.Employee_ID
GROUP BY e.Market_ID
) e ON e.Market_ID = m.Market_ID
答案 1 :(得分:1)
像.........
这样的东西SELECT SUB_Q.Title, SUM(SUB_Q.Tot) FROM
(
SELECT Markets.Title, sum(Purchase.TotalPrice) as Tot
FROM Purchase
INNER JOIN Employees ON Purchase.Employee_ID = Employees.Employee_ID
INNER JOIN Markets ON Employees.Market_ID = Markets.Market_ID
GROUP BY Markets.Title
UNION ALL
SELECT Markets.Title, sum(Employees.Salary) as Tot
FROM Employees
INNER JOIN Markets ON Employees.Market_ID = Markets.Market_ID
GROUP BY Markets.Title
) SUB_Q
GROUP BY SUB_Q.Title
答案 2 :(得分:0)
只需在两个SELECT
之间添加UNION关键字有关UNION的详细信息,请参阅此处:https://msdn.microsoft.com/fr-fr/library/ms180026%28v=sql.120%29.aspx