【问题标题】:Multiply 2 values from different tables and store the result in a new table将不同表中的 2 个值相乘并将结果存储在新表中
【发布时间】:2016-11-18 07:44:54
【问题描述】:

图书(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 来更新它。

【问题讨论】:

  • 如果你存储一个计算值,你引入一个存储、计算的值与原始基础数据不一致的机会.理想情况下,不要存储这些值,除非或直到证明按需计算的性能(如有必要,将逻辑放在视图中)不足。 然后考虑存储该值,但如果可能,请使用内置机制来确保数据库系统自动维护该值,而不是您必须记住重新计算它。

标签: sql sql-server sql-server-2014 calculated-columns computed-field


【解决方案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

【讨论】:

    【解决方案2】:

    我猜你的想法来自这个:

    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
    

    【讨论】:

    • 我尝试在 order_details 中添加新记录(插入 Order_details 值('O02','B01',1))但是当我运行时(从订单中选择 *),计算结果没有更新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-23
    • 2016-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多