我正在使用northwind紧凑版数据库,而我正在尝试提取哪些销售人员赚了多少钱。
因此,我的查询的内部部分工作正常,因为我得到了一个包含总费用的员工ID列表:
select orderCosts."Employee ID", sum(orderCosts.Cost) as OrderCost from
(
select Orders."Order Id",orders."Employee ID", orders."Customer ID", "Order Details"."Unit Price" * "Order Details"."Quantity" as Cost from orders
inner join "Order Details"
On Orders."Order ID" = "Order Details"."Order ID"
) orderCosts
group by ordercosts."Employee ID"
我认为没问题,然后我会尝试将其加入到员工表中,这似乎并不复杂,但现在我收到"The table aliases must be unique. [Name of duplicate alias = employeePerformance]"
错误。我像以前一样嵌入并命名了表格,如下所示:
select Employees."FirstName", Employees."LastName", employeePerformance.OrderCost
from
(
select orderCosts."Employee ID", sum(orderCosts.Cost) as OrderCost from
(
select Orders."Order Id",orders."Employee ID", orders."Customer ID", "Order Details"."Unit Price" * "Order Details"."Quantity" as Cost from orders
inner join "Order Details"
On Orders."Order ID" = "Order Details"."Order ID"
) orderCosts
group by ordercosts."Employee ID"
) employeePerformance
inner join employeePerformance
On Emplyees."Employee ID" = employeePerformance."Employee ID"
我可以看到,我只是宣布一次empployeePerformance,然后试图加入它,所以为什么它认为我已经两次了?
我对SQL很陌生,所以如果我正在做一些愚蠢的事情,请善待!
答案 0 :(得分:1)
我认为你应该在员工上添加一个FROM,在子查询上添加一个连接(如果我理解的话)
select Employees."FirstName", Employees."LastName", employeePerformance.OrderCost
from Employees
INNER JOIN
(
select orderCosts."Employee ID", sum(orderCosts.Cost) as OrderCost from
(
select Orders."Order Id",orders."Employee ID", orders."Customer ID", "Order Details"."Unit Price" * "Order Details"."Quantity" as Cost from orders
inner join "Order Details"
On Orders."Order ID" = "Order Details"."Order ID"
) orderCosts
group by ordercosts."Employee ID"
) employeePerformance
On Employees."Employee ID" = employeePerformance."Employee ID"
因为在您的查询中,您在employeesperformance =>上对employeesPerformance和inner join进行了FROM重复的名称,这是不允许的。
顺便说一下,我认为你的查询可以大大简化:
SELECT e."FirstName", e."LastName", sum(od."Unit Price" * od."Quantity") as OrderCosts
FROM employees e
inner join orders o on o."Employee ID" = e."Employee ID"
inner join "Order Details" od on od."Order ID" = o."Order ID"
group by e."Employee ID", e."FirstName", e."LastName"
如果您希望员工没有订单/订单明细,请使用左连接而不是内连接(并在单价和数量上合并)。
SELECT e."FirstName", e."LastName", sum(coalesce(od."Unit Price", 0) * coalesce(od."Quantity", 0)) as OrderCosts
FROM employees e
left join orders o on o."Employee ID" = e."Employee ID"
left join "Order Details" od on od."Order ID" = o."Order ID"
group by e."Employee ID", e."FirstName", e."LastName"