我必须通过'salesperson'列将两个表组合成不同的列。 到目前为止我遇到的查询问题是一些销售人员的名字是重复的,而右边的表中的一些名称是丢失的。
交易表
salesperson, Profit, Units
John 100 1
John 50 1
Carl 200 2
Matt 300 3
连接表
salesperson, Amount
Carl 100
Lynda 200
Lucy 300
组合表
salesperson, (Amount+Profit), Units(sum)
Carl 300 2
John 150 2
Matt 300 3
Lynda 200 0
Lucy 300 0
这是我到目前为止所得到的
SELECT t.salesperson, SUM(t.profit) + SUM(c.amount), SUM(t.units)
FROM transactions AS t
FULL OUTER JOIN connections as c ON t.salesperson = c.salesperson
GROUP BY t.salesperson
ORDER BY t.salesperson ASC
非常感谢任何帮助。
答案 0 :(得分:3)
SELECT salesperson, SUM(total), SUM(Units)
FROM
(
SELECT salesperson, Amount as total, Units
FROM Transactions
UNION ALL
SELECT salesperson, Profit as total, 0 as Units
FROM Connections
) T
GROUP BY salesperson