Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Substract the price using Case in Mysql

I have 3 tables: training_schedules, training_discounts, and agents.
training_schedules: id, name, agent_id, price.
training_discounts: id, agent_id, schedule_id, discount.
agents: id, name

I try to subtract the price from training_schedules table with the discount column in training_discounts table like this:

SELECT ts.id, name, training_types, DATE_FORMAT(date_start ,'%d/%m/%Y') as date_start, 
                DATE_FORMAT(date_end ,'%d/%m/%Y') as date_end, quota, price, td.discount,
                CASE price WHEN td.agent_id = 2  THEN (price - td.discount) ELSE price END as total   
                FROM training_schedules ts
                LEFT JOIN training_discounts td on ts.id = td.schedule_id GROUP BY td.schedule_id;

But it doesn’t right, the total column is still the same price as before even if agent_id is the same. What can possibly be wrong with my query? Here’s the SQLfiddle if needed: http://sqlfiddle.com/#!9/0cd42d/1/0

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You don’t need to use group by since you are not using any aggregation functions.

SELECT ts.id
  , name
  , training_types
  , DATE_FORMAT(date_start ,'%d/%m/%Y') as date_start
  , DATE_FORMAT(date_end ,'%d/%m/%Y') as date_end
  , quota, price
  , td.discount  
  , CASE WHEN td.agent_id = 2 THEN price - td.discount ELSE price END as total   
FROM training_schedules ts
LEFT JOIN training_discounts td on ts.id = td.schedule_id;

You are also using the select case wrongly. Another option is to use mysql if() function.

if(agent_id = 2, price - td.discount, price) as total 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading