我有四个表,但为此我只需要三个表,并且我想显示customerid,orderid,productid,quantity和总成本,这些不在任何表中但需要计算?到目前为止,我已设法使用订单ID显示一个订单的总成本,但我希望它显示上面提到的所有列
顺序:
order_id(primary key)
customer_id( foreign key)
订单项目:
orderid(fk) + productid(fk) (pk)
quantity
产品:
productid(pk)
price
我所做的是
select orderid, sum(rowcost) as totalcost
from (select o.quantity, o.productid, o.orderid, os.customerid, p.price,
(o.quantity * p.price) as rowcost
from orderline o
inner join order os
on o.orderid = os.orderid
inner join product p
on p.productid = o.productid
where productid = 123)
group by orderid;
现在我希望它显示所有orderid以及productid,customerid,totalcost,orderid和quantity。该列表应遵循customerid订单。
我该怎么做?
当我在select中添加更多变量时,它会给我带来错误。我尝试了很多方法,但都没有。
答案 0 :(得分:0)
select o.quantity, o.productid, o.orderid, os.customerid, p.price,
(o.quantity * p.price) as rowcost,
sum(o.quantity * p.price) over (partition by os.customerid) as totalcost
from orderline o
inner join order os
on o.orderid = os.orderid
inner join product p
on p.productid = o.productid
where p.productid = 123
或者,如果你想在产品上过滤后保持总和正确
select *
from (select o.quantity, o.productid, o.orderid, os.customerid, p.price,
(o.quantity * p.price) as rowcost,
sum(o.quantity * p.price) over (partition by os.customerid) as totalcost
from orderline o
inner join order os
on o.orderid = os.orderid
inner join product p
on p.productid = o.productid)
where productid = 123--or just remove this where clause