tags:

views:

59

answers:

3

Hello,

I want to implement something like Col3 = Col2 + Col1 in SQL.

This is somewhat similar to Excel, where every value in column 3 is sum of corresponding values from column 2 and column 1.

+2  A: 

Yes, you can do it in SQL using the UPDATE command:

UPDATE TABLE table_name
SET col3=col1+col2
WHERE <SOME CONDITION>

This assumes that you already have a table with populated col1 and col2 and you want to populate col3.

codaddict
You can also do it in a SELECT statement - it doesn't have to be just part of an UPDATE
Tim Drisdelle
and actually, storing a calculated value usually breaks normalization rules
Leslie
+2  A: 

Have a look at Computed Columns

A computed column is computed from an expression that can use other columns in the same table. The expression can be a noncomputed column name, constant, function, and any combination of these connected by one or more operators.

Also from CREATE TABLE point J

Something like

CREATE TABLE dbo.mytable 
( low int, high int, myavg AS (low + high)/2 ) ;
astander
+2  A: 

Yes. Provided it is not aggregating data across rows.

assume that col1 and col2 are integers.

SELECT col1, col2, (col1 + col2) as col3 FROM mytable

Tim Drisdelle