Understanding CASE in SELECT Statements
In SQL, the CASE statement offers a flexible approach to conditionally retrieve data based on specific criteria. To understand how CASE works within a SELECT statement, let's consider an example where we want to assign values to a new column based on existing conditions:
Consider the query:
SELECT xxx, yyy, CASE WHEN bbb = 'blackberry' THEN 'blackberry' WHEN sss = 'samsung' THEN 'samsung' ELSE NULL END AS 'Handphone' FROM ( SELECT ???? ..... );
Here, the CASE statement is used to evaluate the values of two columns, bbb and sss. If bbb matches 'blackberry', 'blackberry' is assigned as the value for the new column 'Handphone'. Similarly, if sss matches 'samsung', 'samsung' is assigned. Otherwise, the value is set to NULL.
The output of this query will resemble the following:
name | age | Handphone | xxx1 | yyy1 | blackberry | xxx2 | yyy2 | blackberry |
In this case, 'blackberry' is assigned to 'Handphone' for rows where bbb equals 'blackberry'.
For further reference regarding CASE statement syntax and usage, consult resources such as the MSDN Transact SQL Reference (https://msdn.microsoft.com/en-us/library/ms181765.aspx). Additionally, SQL Server Central (https://www.sqlservercentral.com/) provides a comprehensive collection of resources for SQL Server enthusiasts.
The above is the detailed content of How Can SQL's CASE Statement Be Used to Conditionally Assign Values in SELECT Queries?. For more information, please follow other related articles on the PHP Chinese website!