Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server Calculated Column

I have two columns, both int's, Wins and Losses. I have a calculated column WinPercentage as a decimal(14,3), I want this to be:

WinPercentage = (Wins + Losses) / Wins

What's the syntax for that?

like image 761
Scott Avatar asked Nov 04 '10 00:11

Scott


People also ask

What is calculated column in SQL Server?

A computed column is a virtual column that is not physically stored in the table, unless the column is marked PERSISTED. A computed column expression can use data from other columns to calculate a value for the column to which it belongs.

How do I create a calculated field in SQL Server?

Go to your database, right click on tables, select “New Table” option. Create all columns that you require and to mark any column as computed, select that column and go to column Properties window and write your formula for computed column.

How do I update a computed column in SQL Server?

When altering a computed column the only thing you can do is drop it and re-add it. Show activity on this post. This is one of those situations where it can be easier and faster to just use the diagram feature of SQL Server Management Studio.

How do I sum a calculated column in SQL Server?

The aggregate function SUM is ideal for computing the sum of a column's values. This function is used in a SELECT statement and takes the name of the column whose values you want to sum. If you do not specify any other columns in the SELECT statement, then the sum will be calculated for all records in the table.


1 Answers

CREATE TABLE WinLoss
(
 TeamId int IDENTITY(1,1) NOT NULL,
 Wins int,
 Losses int,
 WinPercentage AS CASE WHEN wins > 0 THEN (Wins + Losses) / Wins ELSE 0 END
)
like image 145
John Hartsock Avatar answered Oct 18 '22 21:10

John Hartsock