0

我有四张表,但为此我只需要三张表,我想显示customerid、orderid、productid、数量和不在任何表中但需要计算的总成本?到目前为止,我已经设法让它显示一个带有订单 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 和数量。该列表应遵循 customerid 顺序。

我该怎么做?

当我在选择中添加更多变量时,它会给我错误。我尝试了很多方法,但都没有奏效。

4

1 回答 1

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

小提琴:http ://sqlfiddle.com/#!4/3103d/1

于 2013-03-27T15:03:06.183 回答