In SQL, the CASE statement allows you to perform conditional evaluations and return different results based on the specified conditions. This is especially useful when you want to categorize or classify data based on certain criteria.
Consider the following example:
SELECT xxx, yyy, CASE WHEN bbb THEN 'blackberry' WHEN sss THEN 'samsung' END FROM ( SELECT ???? ..... )
In this example, the result would display the values of xxx and yyy along with the following:
Name | Age | Handphone |
---|---|---|
xxx1 | yyy1 | blackberry |
xxx2 | yyy2 | blackberry |
For a comprehensive understanding of the CASE statement syntax and usage, refer to credible resources such as Microsoft's Transact-SQL Reference:
https://msdn.microsoft.com/en-us/library/ms181765.aspx
Let's consider a scenario where you want to categorize products in AdventureWorks2012 database based on their list prices:
USE AdventureWorks2012; GO SELECT ProductNumber, Name, "Price Range" = CASE WHEN ListPrice = 0 THEN 'Mfg item - not for resale' WHEN ListPrice < 50 THEN 'Under ' WHEN ListPrice >= 50 AND ListPrice < 250 THEN 'Under 0' WHEN ListPrice >= 250 AND ListPrice < 1000 THEN 'Under 00' ELSE 'Over 00' END FROM Production.Product ORDER BY ProductNumber; GO
This query will output the following result:
ProductNumber | Name | Price Range |
---|---|---|
1 | Bike | Under 0 |
2 | Chair | Under |
3 | Table | Under 0 |
For further exploration of SQL Server, consult the SQL Server Central website:
https://www.sqlservercentral.com/
The above is the detailed content of How Can I Use SQL's CASE Statement to Perform Conditional Evaluations in SELECT Queries?. For more information, please follow other related articles on the PHP Chinese website!