我们需要找出XYZ公司(来自项目)每个项目的总成本。总成本被视为发票明细表中(单位价格*数量)的总和。
要查找每个项目的总成本,您需要在查询中加入3个表:XYZ_PROJECTS使用XYZ_INVOICES(使用PROJECT_NUMBER)和XYZ_INVOICES使用XYZ_INVOICE_DETAILS(使用INVOICE_NUMBER)。
转到SQLWorkshopSQL命令。编写并执行“选择”查询以从XYZ_INVOICE_DETAILS中选择项目编号,项目名称来自XYZ_PROJECTS,sum(c.qty * c.Unit_price)。 (您需要在查询结尾添加“group by project_number,project_name”,因为使用了SUM聚合函数)。运行查询。您的屏幕应如下所示
我用它来加入表,但我不知道如何同时加入3个表。
select *
from XYZ_PROJECTS c
join XYZ_INVOICES do on c.PROJECT_NUMBER = do.PROJECT_NUMBER
select *
from XYZ_INVOICES i
join XYZ_INVOICE_DETAILS do on i.INVOICE_NUMBER = do.INVOICE_NUMBER
也许我做错了。请帮助我。
答案 0 :(得分:1)
select c.project_number, c.project_name, sum(do.qty * do.Unit_price)
from XYZ_PROJECTS c
join XYZ_INVOICES i
on c.PROJECT_NUMBER = i.PROJECT_NUMBER
join XYZ_INVOICE_DETAILS do
on i.INVOICE_NUMBER = do.INVOICE_NUMBER
group by c.project_number, c.project_name
如果您需要包含尚无任何发票的零费用项目,请使用left outer join
保留XYZ_PROJECTS中的所有行:
select c.project_number, c.project_name, sum(do.qty * do.Unit_price)
from XYZ_PROJECTS c
left join XYZ_INVOICES i
on c.PROJECT_NUMBER = i.PROJECT_NUMBER
left join XYZ_INVOICE_DETAILS do
on i.INVOICE_NUMBER = do.INVOICE_NUMBER
group by c.project_number, c.project_name