简体   繁体   English

SQL。 这涉及将来自不同表的两列相乘

[英]SQL. This one involves multiplying two columns from different tables

First I have to find the Salesman ID, salespersons names (first and last), their SIN number, the quantity sold, the unit price and the total $ in sales (and I have to label this field as TotalSales) for each product. 首先,我必须找到每个产品的推销员ID,推销员姓名(姓氏和名字),他们的SIN号,所售数量,单价和总销售额(我必须将此字段标记为TotalSales)。

Here is the data: 数据如下:

在此处输入图片说明

Here is what I have done so far, let me know if it is wrong: 这是我到目前为止所做的,如果有错,请告诉我:

SELECT 
    s.SalesmanID, s.FirstName, s.LastName, s.SIN, 
    ps.QuantitySold, ps.UnitSalesPrice, 
    (this is where I’m stuck, I must have to create a new column called TotalSales here)

Let me know if you can help! 让我知道您能否提供帮助!

SELECT s.SalesmanID, max(s.FirstName) first_name, max(s.LastName) last_name, max(s.SIN) sin, sum(ps.QuantitySold) sold_qty, sum(ps.quantitysold * ps.UnitSalesPrice) total_sales_AMT from salesmen s join productsales PS on s.salesmanid = PS.sellerid group by s.salesmanid

You need to do a join with a group by in order to total the sales quantity and sales prices at the salesman level. 您需要与一个组进行加入,以便在业务员级别上汇总销售数量和销售价格。 See code above. 参见上面的代码。

The reason for the join and group by is because i assume that there is a one to many relationship between the salesmen and productsales. 加入和分组的原因是因为我认为销售员和产品销售之间存在一对多的关系。

If you need to do it at the salesman and product level then you want to expand the grouping. 如果需要在业务员和产品级别执行此操作,则需要扩展分组。 See below. 见下文。

SELECT s.SalesmanID, ps.productid, max(s.FirstName) first_name, max(s.LastName) last_name, max(s.SIN) sin, sum(ps.QuantitySold) sold_qty, sum(ps.quantitysold * ps.UnitSalesPrice) total_sales_AMT from salesmen s join productsales PS on s.salesmanid = PS.sellerid group by s.salesmanid, ps.productid

One more note is that replace the join with a left outer join if you want to get all salesmen and not only the ones that had a sale 还有一点需要注意的是,如果您想获得所有推销员,而不仅仅是获得销售的推销员,请用左外部联接替换该联接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM