views:

158

answers:

1

I have written a query to Select sales values from a database and apply discounts if there were any used. The discounts are either a percentage or just a flat-value. My Query applies the discounts (first case statement) and then pulls the amount that was applied.

It got me thinking if it was possible to get this done in one case statement.

Query:

SELECT
SUM(CASE 
 WHEN td.Transaction_ID IS NULL
  THEN p.Sale
 WHEN td.Transaction_ID IS NOT NULL AND d.Discount_Type = '0'
  THEN p.Sale - (p.Sale * (dp.Discount_Percent/100))
 ELSE
  p.Sale - dv.Discount_Value
END) PriceDiscounted,
SUM(CASE
 WHEN td.Transaction_ID IS NOT NULL AND d.Discount_Type = '0'
  THEN (p.Sale * (dp.Discount_Percent/100))
 WHEN td.Transaction_ID IS NOT NULL AND d.Discount_Type = '1'
  THEN dv.Discount_Value
 ELSE '0'
END) Discount
+1  A: 

No a CASE statement inside a SELECT is a function and can only return one value. You could implement this inside a Stored Procedure in which you could use CASE or IF THEN.

MindStalker
does that apply to all conditional statements in MySQL?
Derek Adair
Yes, CASE statements inside a SELECT only allow a value for THEN or ELSE, while the CASE statement in a stored procedure (or stored function) can hold any expression.
MindStalker
I should add, that a Stored Procedure CASE can't loop through the multiple records of a table as a regular SELECT, you have to use a cursor. So performance benefits would be lost.
MindStalker