Case in Select Statement

fadzli feizal picture fadzli feizal · Jan 7, 2013 · Viewed 798.5k times · Source

I have an SQL statement that has a CASE from SELECT and I just can't get it right. Can you guys show me an example of CASE where the cases are the conditions and the results are from the cases. For example:

     Select xxx, yyy
     case : desc case when bbb then 'blackberry';
     when sss then 'samsung';
     end 
     from (select ???? .....

where the results show

 name                         age       handphone
xxx1                         yyy1      blackberry
xxx2                         yyy2      blackberry

Answer

NuNn DaDdY picture NuNn DaDdY · Jan 7, 2013

The MSDN is a good reference for these type of questions regarding syntax and usage. This is from the Transact SQL Reference - CASE page.

http://msdn.microsoft.com/en-us/library/ms181765.aspx

USE AdventureWorks2012;
GO
SELECT   ProductNumber, Name, "Price Range" = 
  CASE 
     WHEN ListPrice =  0 THEN 'Mfg item - not for resale'
     WHEN ListPrice < 50 THEN 'Under $50'
     WHEN ListPrice >= 50 and ListPrice < 250 THEN 'Under $250'
     WHEN ListPrice >= 250 and ListPrice < 1000 THEN 'Under $1000'
     ELSE 'Over $1000'
  END
FROM Production.Product
ORDER BY ProductNumber ;
GO

Another good site you may want to check out if you're using SQL Server is SQL Server Central. This has a large variety of resources available for whatever area of SQL Server you would like to learn.