Syntax:
--SIMPLE CASE EXPRESSION
SELECT <columns>
CASE <input_expression>
WHEN <possible_input_expression_value> THEN <desired_expression>
WHEN <possible_input_expression_value> THEN <desired_expression>
ELSE <default_expression>
END AS <desired_column_name>
FROM…WHERE…ETC
--SEARCHED CASE EXPRESSION
SELECT <columns>
CASE
WHEN <evaluation> THEN <desired_expression>
WHEN <evaluation> THEN <desired_expression>
ELSE <default_expression>
END AS <desired_column_name>
FROM…WHERE…ETC
Examples:
SELECT DATEPART(MONTH, ct.TransactionDate),
CASE
WHEN DATEPART(MONTH, TransactionDate) BETWEEN 3 AND 5
THEN 'Spring'
WHEN DATEPART(MONTH, TransactionDate) BETWEEN 6 AND 8
THEN 'Summer'
WHEN DATEPART(MONTH, TransactionDate) BETWEEN 9 AND 11
THEN 'Fall'
WHEN DATEPART(MONTH, TransactionDate) = 12
OR DATEPART(MONTH, TransactionDate) BETWEEN 1 AND 2
THEN 'Winter'
END AS [Season],
*
FROM Sales.CustomerTransactions ct
WHERE ct.TransactionDate BETWEEN '2013-01-01' AND '2013-12-31'
AND ct.CustomerID = 801;
SELECT CASE ct.TransactionTypeID
WHEN 1
THEN 'Invoice'
WHEN 3
THEN 'Payment'
END AS [TransType],
*
FROM Sales.CustomerTransactions ct
WHERE ct.TransactionDate BETWEEN '2013-01-01' AND '2013-12-31'
AND ct.CustomerID = 801;
