A select list can contain expressions that are built by applying operators to one or more simple expressions. This allows result sets to contain values that do not exist in the base tables, but are calculated from the values stored in the base tables. These result set columns are called derived columns, and include:
SELECT ROUND( (UnitPrice * .9), 2) AS DiscountPrice
FROM Products
WHERE ProductID = 58
SELECT ( CAST(ProductID AS VARCHAR(10)) + ': '
+ ProductName ) AS ProductIDName
FROM Products
SELECT ProductID, ProductName,
CASE CategoryID
WHEN 1 THEN ROUND( (UnitPrice * .6), 2)
WHEN 2 THEN ROUND( (UnitPrice * .7), 2)
WHEN 3 THEN ROUND( (UnitPrice * .8), 2)
ELSE ROUND( (UnitPrice * .9), 2)
END AS DiscountPrice
FROM Products
SELECT Prd.ProductID, Prd.ProductName,
( SELECT SUM(OD.UnitPrice * OD.Quantity)
FROM Northwind.dbo.[Order Details] AS OD
WHERE OD.ProductID = Prd.ProductID
) AS SumOfSales
FROM Northwind.dbo.Products AS Prd
ORDER BY Prd.ProductID
Calculations and computations can be performed with data by using numeric columns or numeric constants in a select list with arithmetic operators, functions, conversions, or nested queries. Arithmetic operators let you add, subtract, multiply, and divide numeric data.
These arithmetic operators are supported.
Symbol | Operation |
---|---|
+ | Addition |
- | Subtraction |
/ | Division |
* | Multiplication |
% | Modulo |
The arithmetic operators that perform addition, subtraction, division, and multiplication can be used on any numeric column or expression ( int, smallint, tinyint, decimal, numeric, float, real, money, or smallmoney). The modulo operator can only be used on int, smallint, or tinyint columns or expressions.
Arithmetic operations can also be performed on datetime and smalldatetime columns using the date functions or regular addition or subtraction arithmetic operators.
You can use arithmetic operators to perform computations involving one or more columns. The use of constants in arithmetic expressions is optional, as shown in this example:
SELECT ProductID, ProductName,
UnitPrice * UnitsInStock AS InventoryValue
FROM Northwind.dbo.Products
FROM | SELECT |
Operators | Join Fundamentals |
Subquery Fundamentals | + (Add) |
- (Subtract) | Functions |