预订(B_ID为PK)
| B_ID | Name | Unit_Price|
|------+---------+-----------|
| B01 | Math | 25 |
| B02 | Science | 34 |
订单(O_ID为PK)
| O_ID | Date | Total_Price |
|------+---------+-------------|
| O01 | 12/1/16 | NULL |
| O02 | 20/3/16 | NULL |
订单Detais (O_ID,B_ID是复合PK,其中两个ID都是上表中的FK)
| O_ID | B_ID | Quantity |
|------+------+-----------|
| O01 | B01 | 2 |
| O01 | B02 | 1 |
| O02 | B02 | 5 |
如何通过将NULL替换为计算结果,将计算插入Total_Price
(Unit_Price
* Quantity
)。我尝试过使用CTE来解决它但我不喜欢在添加新记录(Exp:O03)时我需要再次运行CTE来更新它。
答案 0 :(得分:0)
根据@Damien的评论,如果您决定不存储计算值,则可以尝试使用以下查询来计算每个订单的总价格:
SELECT o.O_ID,
SUM(od.Quantity * b.Unit_Price) AS Total_Price
FROM Order o
LEFT JOIN Order_Details od
ON o.O_ID = od.O_ID
LEFT JOIN Book b
ON od.B_ID = b.B_ID
GROUP BY o.O_ID
答案 1 :(得分:0)
我猜你从这个想法得到了colud:
create table book (b_id char(10),name char(20),Unit_Price int)
create table orders(o_id char(10),Date varchar(10),Total_Price int)
Create table Order_details(o_id char(10),b_id char(10),quantity int)
insert into book values ('B01','Math' ,25);
insert into book values ('B02','Science',34);
INSERT INTO orders values ( 'O01','12/1/16',NULL)
INSERT INTO orders values ('O02','20/3/16',NULL)
Insert into order_details values('O01','B01',2);
Insert into order_details values('O01','B02',1);
Insert into order_details values('O02','B02',5);
declare @total int, @o_id char(10)
declare c cursor for
select sum(a.unit_price * b.quantity),b.o_id from book a join order_details b on a.b_id=b.b_id group by b.o_id
open c
fetch next from c into @total,@o_id
while @@FETCH_STATUS=0
begin
update orders set total_price=@total where o_id=@o_id
fetch next from c into @total,@o_id
end
close c
deallocate c
select * from orders