我正在尝试回答以下问题: “对于每个推销员,列出他/她的销售额以及那些销售额超过其销售额的推销员的平均销售额。
select sum(p.price * d.qty)
from salesman s
join invoices i on (i.salesman = s.salesman)
join detail d on (d.ino = i.ino)
join parts p on (p.pno = d.pno)
where ---------(
select sum(p.price * d.qty)
from salesman s
join invoices i on (i.salesman = s.salesman)
join detail d on (d.ino = i.ino)
join parts p on (p.pno = d.pno)
)
group by s.salesman
order by s.salesman
我不知道如何将其他所有销售与我从当前行获得的销售进行比较,并为每个销售员重复这一操作
推销员通过一些表格链接起来,以了解零件的成本和销售数量
感谢您的帮助
答案 0 :(得分:1)
您从每个销售人员的销售开始:
select i.salesman, sum(p.price * d.qty)
from invoices i join
detail d
on d.ino = i.ino join
parts p
on p.pno = d.pno
group by i.salesmane;
然后,您可以使用窗口函数获取平均值:
select i.salesman,
sum(p.price * d.qty),
avg(sum(p.price * d.qty)) over (order by sum(p.price * d.qty) rows between 1 following and unbounded following)
from invoices i join
detail d
on d.ino = i.ino join
parts p
on p.pno = d.pno
group by i.salesmane;
答案 1 :(得分:0)
尝试创建一个临时表#TempSales,其中包含每个推销员的总销售额 #将在tempdb数据库中创建一个临时表,如果您自己不删除它,则在用户会话关闭时将被删除 您可以在一个事务中运行以下整个查询。
{ 选择s.salesman,sum(p.price * d.qty)作为TotalSales 进入#TempSales 从推销员的 将发票i加入(i.salesman = s.salesman) 在(d.ino = i.ino)上加入细节d 连接零件p on(p.pno = d.pno) s.saleman分组
select s.Salesman,TotalSales,(select avg(TotalSales) from #TempSales t where t.salesman <> s.salesman and t.TotalSales > s.TotalSales) as AverageSales
from #TempSales
order by s.salesman
drop table #TempSales
}