我正在尝试编写一个查询,该查询从employee_id列表中进行选择,并查找重复的图书购买(book_id)和相关的成本节省(list_price)。如果存在重复,则需要将重复book_id的数量的总和加起来。
因此,如果某人有一本与他们的employee_id相关的成本为10美元的图书,并且该图书再次提供给他们,他们就不必购买,而且可以节省10美元。如果再次发生这种情况,可以节省20美元。
我尝试过> 1但是我似乎无法正确查询查询以准确计算节省。
感谢任何帮助。
答案 0 :(得分:0)
首先,
select employee_id, book_id, count(*)
from book_purchases
group by employee_id, book_id
having count(*) > 1
获取您需要的列表。
如果我们不必担心价格变动,那么我们只需添加一两列即可获得:
select employee_id, book_id,
count(*) as copies_purchased,
sum(list_price) as total_spent,
count(*) - 1 as copies_unnecessarily_purchased,
(count(*) - 1) * avg(list_price) as amount_overspent
from book_purchases
group by employee_id, book_id
having count(*) > 1
当然,您可以加入员工并预订表格以获取名称和标题,以便稍微减少结果。
要获得每位员工超支的总金额,您可以这样包装上述查询:
select a.employee_id, sum(a.amount_overspent) as total_amount_overspent
from (
select employee_id, book_id,
count(*) as copies_purchased,
sum(list_price) as total_spent,
count(*) - 1 as copies_unnecessarily_purchased,
(count(*) - 1) * avg(list_price) as amount_overspent
from book_purchases
group by employee_id, book_id
having count(*) > 1
) as a
group by a.employee_id
最后,我继续前进,加入了一张我认为你在我工作时的员工桌:
select a.employee_id, emp.employee_name, sum(a.amount_overspent) as total_amount_overspent
from (
select employee_id, book_id,
count(*) as copies_purchased,
sum(list_price) as total_spent,
count(*) - 1 as copies_unnecessarily_purchased,
(count(*) - 1) * avg(list_price) as amount_overspent
from book_purchases
group by employee_id, book_id
having count(*) > 1
) as a
inner join employee as emp on emp.employee_id = a.employee_id
group by a.employee_id, emp.employee_name
要明确的是,这些不是四个单独的查询;它们只是构建您最后看到的单个查询的中间阶段。
我希望这会有所帮助。