0

私は4つのテーブルを持っていますが、これには3つのテーブルしか必要ありません.customerid、orderid、productid、quantity、およびテーブルにはないが計算する必要がある総コストを表示したいですか? これまでのところ、注文IDを持つ1つの注文の合計費用を表示することができましたが、上記のすべての列を表示したい

注文:

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;

ここで、productid、customerid、totalcost、orderid、および amount とともにすべての orderid を表示したいと考えています。リストは顧客 ID の順序に従う必要があります。

どうすればいいですか?

選択にさらに変数を追加すると、エラーが発生します。私は多くの方法を試しましたが、どれもうまくいきませんでした。

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 に答える