简体   繁体   中英

Create a table column as a sum of two columns in sql

I have a table, and one of the columns is total_price, which stores the sum of prices of items which are stored in another table. I want to know how to do this in SQL. I want the total price column to calculate the sum of prices automatically and store in its column. In other words, I need a column which sums the required values and stores it by default.

Example:

Line item table has a quantity,pid and total price field.

Product table has a pid and price field.

The total price field in line item table should store (lineitem.quantity*product.price) value.

Use this query to create a table with col3 as sum of col1 and col2:

    CREATE TABLE [dbo].[Emp](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](50),
    [Price] [float] NULL,
    [Qty] [float] NULL,
    [total]  AS ([Price]*[Qty])
) ON [PRIMARY]

If you need to store it, you could still create a trigger.

create trigger UpdateMyColumn before insert on [yourtable] for each row
begin set new.Col3 = Col1 * Col2;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM