Using the CASE Expression in SQL Queries @ JDJ

ajax 同时被 2 个专栏收录
779 篇文章 0 订阅
964 篇文章 0 订阅
<script type="text/javascript"> </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
<script type="text/javascript"> </script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>

  the DBMS (database management system) is often faster at performing calculations like summing up or averaging the values in a column of numbers than, for instance, the application server. However, there are many CASEs in which performing the same calculation on all of the data in a column will not provide the correct result.

  This article will show you how to use the CASE expression in SQL Queries to more flexibly perform aggregate calculations and set values based on a logical statement.

  An example of the need to apply the CASE expression in an aggregate function is an online shopping cart with several item-specific options that, depending on the options chosen, change the way an item's price is added to the cart and, therefore, the final total price of the order. I will discuss a shopping cart for an online store that requires variable pricing within four option areas. the price calculation of the final order will vary depending on the setting of each option.

  the example store sells items including artwork, books, gifts, events, and memberships. It's a dynamic store allowing administrators to add and delete categories, subcategories, and items. One item can exist in as many categories as the administrator would like. individual items within a category may be subject to different pricing options. With these requirements, the programmer does not know what categories and subcategories will exist in the store in the future or under what category or pricing options an item will be placed. therefore, options must be set at the item level and be available for administrators to set and change.

  Requirements for the example store include the ability of administrators to choose options in these four areas:

  Sale price: individual items may or may not be on sale. the database table contains a column for regular price and sale price and an additional flag column named SaleItem, allowing the administrator simply to change the SaleItem setting rather than change the value for regular price each time the item goes on sale.

  Shipping: Shipping cost is calculated based on the shopping cart total. However, administrators can select certain items such as memberships so that they do not carry a shipping charge.

  Member and employee discount: the organization has members and employees who are entitled to different discounts on purchases from the store. However, some items do not qualify for discounting under any circumstance.

  Sales taxes: Some items are taxed and some are not. For example, tax law does not require sales tax on memberships.

  Overview of the SUM Function

  Programmers often use the SUM() aggregate function to total the numbers contained in a database column. For instance, in a shopping cart, you might use the sum function as follows:

  SELECT Name, SUM(Price) as Total

  FROM Item

  WHERE ItemID=#SomeValue#

  the database will return rows of records, each containing the Name of the item and the sum total of the values found in the Price column for the records selected. Each row will contain the same value for Total. If no columns are selected, the query will return one row with the value of Total.

  Based on the discussion above, simply totaling the prices in the Price column will not work for this shopping cart. For example, if the customer chooses an item that's on sale, the price in the SalePrice column must be used for that item. You might choose to solve this problem with CFML as follows:

 

 

 

 

 

 

 

 

  This solution does not rely on SQL to total the item prices. instead, the application loops through all of the items selected and adds them up in a CFLOOP loop. However, SQL does provide an elegant way to perform the same calculation Using the SUM aggregate function in combination with the CASE expression. the total price of the items, taking into account those that are on sale, is included in the returned table Using this method.

  Overview of the CASE Expression

  the CASE expression, introduced in SQL-92, provides the programmer with the ability to choose one of multiple values based on a logical expression. the value added to the item total of our shopping cart Using the SUM() aggregate function is the value in the Price column for an item that is not on sale and the value in the SalePrice column for an item that is on sale. the CASE expression is supported by SQL Server, MySQL, PostgreSQL, and Oracle beginning with Oracle8i.

  the SQL query to total the price of the items, taking into account those that are on sale, looks like:

  SELECT

  SUM(CASE WHEN SaleItem=1 theN SalePrice ELSE Price END)

  FROM Item

  as TotalPrice

  WHERE Item.CartID=#SomeValue#

  in the query above, the item is evaluated to see if SaleItem is 1. If it is, the SalePrice column is used for that item in calculating the total price. If not, the Price column is used.

  Database Tables

  the critical database tables for our cart include Item, Cart, CartItems, Tax, Discount, and Shipping.

  the important columns in each table are:

  Item: ItemID (primary key), Price, SalePrice, SaleItem (1 or 0), Shipping (1 or 0), Discount (1 or 0), Tax (1 or 0)

  Cart: CartID (primary key)

  CartItems: CartItemID(primary key), CartID, ItemID, Quantity

  Tax: Pct, Gov

  Discount: DiscountID (primary key), Name, Pct

  Shipping: MinTotal, MaxTotal, ShipCost

  the columns SaleItem, Shipping, Discount, and Tax, in the Item table, are switches used to turn each of the item pricing options on and off. For instance, if SaleItem is 1, then the product will be priced at the sale price. Of course, there are a number of other columns in the Item table that contain the content required to display the item.

  the Cart table stores keys to identify carts and to find items in a cart. A Cart record is created when a customer adds his first item to a cart. the CartID is stored to allow for the retrieval of cart items after the cart session has expired.

  the CartItems table allows for the joining of the cart with the items in the cart. It also stores the quantity of the item to be included in the cart.

  the Tax table stores the abbreviated names and the percent sales tax for each government requiring the addition of tax.

  the Discount table stores the names of member or employee discounts and their respective discount percentage.

  the Shipping table stores min/max ranges of item totals and the corresponding shipping charge to be applied to the order based on the order total falling between or being equal to the min and/or max total.

  Shopping Cart Calculation Example

  Before summing the cart for the customer prior to final checkout Using the SUM() aggregate function and CASE expression, information necessary for the calculation of the cart total is retrieved from the database as follows.

  First, get the discount percentage based on the member type (individual, student, etc.) or employee status selected by the customer in the checkout form. Optionally, if a member and/or employee database exists, you can verify the member type or employee status from the employee or member records.

 

  SELECT Name, Pct

  FROM Discount

  WHERE DiscountID='#Form.DiscountID#'

 

  Next, get the sales tax based on the state to which the order will be shipped. the customer has provided a "bill to" address and, optionally, a "ship to" address. Sales tax is based on the "ship to" state. If the "bill to" address is the same as the "ship to" address, the customer completes only the "bill to" address form. At this point, check to see if the form field Form.sState (the "ship to" state) is not available or is null. If either is true we use Form.State (the "bill to" state) to calculate sales taxes because the "ship to" address and the "bill to" address are the same. If both are false, use the "ship to" state.

  ined('Form.sState') or Form.sState is "">

  ingState=Form.State>

 

  ingState=Form.sState>

 

 

  SELECT Pct

  FROM Tax

  WHERE Gov = '#ShippingState#'

 

  Finally, check to see if sales tax applies. If there are no sales tax records for the state to which the order will be shipped, GetSalesTaxes.RecordCount will be 0 and sales tax will not be added.

 

 

 

 

 

  Now it is known what discount to apply and what percentage of the total price of the taxable items will be added to the bill for sales tax. the real work Using the CASE expression can begin.

  Elsewhere in the application when the customer places his or her first item into the cart, Session.Cart is created and set to a unique value generated by the CreateUUID() function. Because records in the CartItems table contain the field CartID that is set to a value equal to Session.Cart as items are added to the cart by the shopper, Using Session.Cart directly in the query GetCartItems detailed below works as long as Session.Cart exists.

  However, Session.Cart is deleted after final checkout to end the cart session. in order to re-use the following code to process orders after the cart session is over and Session.Cart no longer exists, or to extend the life of the cart beyond the existence of Session.Cart if desired, create CartSumCartID and use it in the GetCartItems query in place of Session.Cart. This allows the value of CartSumCartID to be set Using a database record instead of Session.Cart (e.g., the value in the CartID field in the Cart table described in the Database Tables section above). For now, just set CartSumCartID to Session.Cart because in this example the query GetCartItems is being used prior to final checkout.

 

  the query at the heart of the shopping cart is as follows:

 

 

  SELECT CartItems.CartItemID, CartItems.Quantity, Item.*,

  the following subquery calculates the value for TotalPrice.

  Join Item and CartItems to find items contained in the cart.

  If it is a sale item use the sale price, if not use the price.

  (SELECT

  SUM(CASE

  WHEN SaleItem=1

  theN Quantity*SalePrice

  ELSE Quantity*Price

  END) FROM (Item inNER JOin CartItems ON Item.ItemID = CartItems.ItemID)

  WHERE CartItems.CartID='#CartSumCartID#') as TotalPrice,

  To calculate the total after discounting. (TotalDiscountPrice) use the following nested CASE expressions in the subquery below.

  If it is a sale item use the sale price, if not use the price.

  If discounting is allowed for this item multiply total item price (quantity*price) by 1-Discount; otherwise, use the total item price without discount.

  (SELECT

  SUM(CASE

  WHEN SaleItem=1

  theN CASE WHEN Discount=1 theN Quantity*SalePrice*(1-#Discount#) ELSE Quantity*SalePrice

  END

  ELSE CASE WHEN Discount=1 theN Quantity*Price*(1-#Discount#) ELSE Quantity*Price END

  END) FROM (Item inNER JOin CartItems ON Item.ItemID = CartItems.ItemID)

  WHERE CartItems.CartID='#CartSumCartID#') as TotalDiscountPrice,

  Next calculate SalesTax.

  TaxRate was set above.

  Apply sale prices and discounts before calculating sales tax.

  If the item is nontaxable, 0 is added to SalesTax.

  (SELECT

  SUM(CASE

  WHEN Tax=1

  theN CASE WHEN SaleItem=1

  theN CASE WHEN Discount=1 theN Quantity*SalePrice*(1-#Discount#)*#TaxRate#*1/100 ELSE

  Quantity*SalePrice*#TaxRate#*1/100 END

  ELSE CASE WHEN Discount=1 theN Quantity*Price*(1-#Discount#)*#TaxRate#*1/100 ELSE

  Quantity*Price*#TaxRate#*1/100 END

  END

  ELSE 0

  END) FROM (Item inNER JOin CartItems ON Item.ItemID = CartItems.ItemID) WHERE

  CartItems.CartID='#CartSumCartID#') as SalesTax,

  Now see if the total item price is to be used in the calculation of shipping charges by again Using nested CASE expressions.

  If the item is not to be used in the shipping calculation, it is added as 0.

  (SELECT

  SUM(CASE

  WHEN Shipping=1

  theN CASE WHEN SaleItem=1

  theN CASE WHEN Discount=1 theN Quantity*SalePrice*(1-#Discount#) ELSE Quantity*SalePrice

  END

  ELSE CASE WHEN Discount=1 theN Quantity*Price*(1-#Discount#) ELSE Quantity*Price END

  END

  ELSE 0

  END) FROM (Item inNER JOin CartItems ON Item.ItemID = CartItems.ItemID) WHERE

  CartItems.CartID='#CartSumCartID#') as TotalShippingPrice

  Finish the query.

  FROM (Item inNER JOin CartItems ON Item.ItemID = CartItems.ItemID)

  WHERE CartItems.CartID='#CartSumCartID#'

  ORDER BY Name

 

  the table returned contains rows of items in the customer's cart with the information about each item and the quantity ordered. in addition, each row of the table includes the item total prior to discount (TotalPrice), the item total after discount (TotalDiscountedPrice), the sales tax to be added to the order (SalesTax), and the item total for items that are to be used in the calculation of shipping charges (TotalShippingPrice).

  there is one last task to complete prior to displaying the cart summary to the customer - determining shipping cost. Shipping cost is determined by the value of GetCartItems.TotalShippingPrice. ShipCost is returned by the following query where the value of GetCartItems.TotalShippingPrice falls between or is equal to MinTotal and/or MaxTotal in the Shipping table.

  ingFee" DATASOURCE="#Application.Datasource#">

  SELECT ShipCost

  FROM Shipping

  WHERE #GetCartItems.TotalShippingPrice# >= MinTotal

  and #GetCartItems.TotalShippingPrice# <= MaxTotal

 

  Later the shipping cost and sales tax will be added to the total and passed along to the display template.

  Conclusion

  the CASE expression allows the programmer to create Queries that use logical expressions to determine what value to use and/or what calculation to perform. Used in a subquery, the CASE expression allows for the generation of multiple values from the same data set. the CASE expression is, in many instances, a viable alternative to post query loops and calculations. Application of the CASE expression can help you make the most of SQL in development p

<script type="text/javascript"> </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
<script type="text/javascript"> </script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 扫一扫,分享海报

参与评论 您还未登录,请先 登录 后发表或查看评论
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值