2013-03-27 45 views
0

我有四張桌子,但爲此我只需要三張桌子,我想要顯示不在任何表格中但需要計算的客戶,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; 

現在,我想這與產品ID,客戶ID,TOTALCOST,訂單ID和數量一起顯示所有orderids。該清單應遵循customerid訂單。

我該怎麼做?

當我在select中添加更多變量時,它給了我錯誤。我嘗試了很多方法,但都沒有成功。

回答

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

+0

是的但是我已經嘗試過它沒有工作,也希望它顯示所有產品的總數不僅僅是一個。 – user2216093 2013-03-28 08:21:01

+0

@ user2216093你能定義「沒有工作」嗎?你原來的SQL有'where productid = 123',所以我保留這個..你可以刪除它,如果你想要所有productid的。如果您的意思是它沒有提供所需的輸出,爲每個表格添加示例數據以及所需的輸出,可能會有所幫助。 – DazzaL 2013-03-28 10:33:18

+0

它不起作用,因爲它給出了一個錯誤,我在發佈之前執行了該查詢並且它不起作用 – user2216093 2013-03-28 11:01:21