1

图书(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     |

订单详情(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 来更新它。

4

2 回答 2

1

根据@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
于 2016-11-18T07:52:22.283 回答
1

我猜你是从这个想法中得到的:

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
于 2016-11-18T08:03:59.373 回答