AlphaPress Publishing
P.O. Box 5942 Albany, NY 12205
Tel: 518-250-3890
Email: alphapress@hotmail.com  


  
Click to buy this book from Amazon

Section Menu 

News

Pindaro is now working on a comprehensive book on SQL Server 2014.  For any comments you can email the author at alphapress@hotmail.com.

  

 

 

How to use calculated fields with multiple conditions

To contact the author click here

This article is from the book "Access 2007 Pure SQL

To download the sample database click here


 

Calculated fields with multiple conditions

Provide customers with different discounts based on their city

Discussion:

Suppose we want to provide a 20% discount for products from SupplierID=1, 15% for those from SupplierID=2, 18% for those from SupplierID=3, and 25% for those from SupplierID=4.  In addition, we might want to provide a 10% discount for all of the rest of the products regardless of supplier.  The switch function comes to the rescue here, providing the flexibility to give us the results we need.

 

Code:

SELECT productname,

SWITCH(

SupplierID = 1,                       ProductUnitPrice*(1-0.2),

SupplierID = 2,                       ProductUnitPrice*(1-0.15),

SupplierID = 3,                       ProductUnitPrice*(1-0.18),

SupplierID = 4,                       ProductUnitPrice*(1-0.25),

TRUE,                                     ProductUnitPrice*(1-0.1)

)

AS ProductPrice

FROM Products

 

Result: