Nested CASE statements in MySQL - mysql

My first time working with CASE Logic in SQL statements. Everything works if I remove the CASE statements, so the SQL is valid without it.
I need to calculate the total item price based on a couple of things.
If "Sales Price" is active AND "Option Upcharge" has a value, the total is: Qty * (Sales Price + Option Upcharge)
If "Sales Price is inactive AND "Option Upcharge" has a value, the total is: Qty * (Price + Option Upcharge)
If "Sales Price" is active AND "Option Upcharge" has NO value, the total is: Qty * Sales Price
If "Sales Price is inactive AND "Option Upcharge" has NO value, the total is: Qty * Price
If no Option was added, the value for tblproduct_options.option_upcharge is NULL in the output.
Thanks for the help.
Brett
Here is my SQL:
SELECT tblshopping_cart.session_id, tblshopping_cart.product_id, tblshopping_cart.product_qty, tblshopping_cart.product_option, tblproducts.product_title, tblproducts.product_price, tblproducts.product_sale_price_status, tblproducts.product_sale_price, tblproduct_options.option_text, tblproduct_options.option_upcharge,
CASE
WHEN (tblproducts.product_sale_price_status = 'Y')
CASE
WHEN (tblproduct_options.option_upcharge IS NOT NULL)
THEN (tblshopping_cart.product_qty * (tblproducts.product_sale_price + tblproduct_options.option_upcharge))
ELSE (tblshopping_cart.product_qty * tblproducts.product_sale_price)
END
ELSE
CASE
WHEN (tblproduct_options.option_upchage IS NOT NULL)
THEN (tblshopping_cart.product_qty * (tblproducts.product_price + tblproduct_options.option_upcharge))
ELSE (tblshopping_cart.product_qty * tblproducts.product_price)
END
END AS product_total
FROM tblshopping_cart
INNER JOIN tblproducts ON tblshopping_cart.product_id = tblproducts.product_id
LEFT JOIN tblproduct_options ON tblshopping_cart.product_option = tblproduct_options.option_product_id
ORDER BY tblshopping_cart.product_qty ASC
It fails with with message:
CASE
WHEN (tblproduct_options.option_upcharge IS NOT NULL)
THEN (tblshopping_' at line 4

You are missing a THEN in your first CASE Statement. (sorry I had to add table aliases)
SELECT sc.session_id
, sc.product_id
, sc.product_qty
, sc.product_option
, p.product_title
, p.product_price
, p.product_sale_price_status
, p.product_sale_price
, po.option_text
, po.option_upcharge
, CASE
WHEN (p.product_sale_price_status = 'Y')
THEN <-- add this
CASE
WHEN (po.option_upcharge IS NOT NULL)
THEN (sc.product_qty * (p.product_sale_price + po.option_upcharge))
ELSE (sc.product_qty * p.product_sale_price)
END
ELSE
CASE
WHEN (po.option_upchage IS NOT NULL)
THEN (sc.product_qty * (p.product_price + po.option_upcharge))
ELSE (sc.product_qty * p.product_price)
END
END AS product_total
FROM tblshopping_cart sc
INNER JOIN tblproducts p
ON sc.product_id = p.product_id
LEFT JOIN tblproduct_options po
ON sc.product_option = po.option_product_id
ORDER BY sc.product_qty ASC

It looks like you're missing THEN in the outer CASE:
CASE
WHEN (tblproducts.product_sale_price_status = 'Y') THEN
^^^^ add this

I think your problem is the way you write you case.
You missed a THEN after your first when. You also missed a END.
CASE
WHEN (tblproducts.product_sale_price_status = 'Y')
THEN
CASE
WHEN (tblproduct_options.option_upcharge IS NOT NULL)
THEN (tblshopping_cart.product_qty * (tblproducts.product_sale_price + tblproduct_options.option_upcharge))
ELSE (tblshopping_cart.product_qty * tblproducts.product_sale_price)
END
ELSE
CASE
WHEN (tblproduct_options.option_upchage IS NOT NULL)
THEN (tblshopping_cart.product_qty * (tblproducts.product_price + tblproduct_options.option_upcharge))
ELSE (tblshopping_cart.product_qty * tblproducts.product_price)
END
END AS product_total

Related

if statement mySQL

I am trying to figure out how to do an if statement that will essentially calculate the stock of an item based on the dates in the tp_rental table.
I was hoping to do something like :
if Date_Due has an entry but Date_Returned does not
then set stock -1
if Date_Due has an entry and Date_returned has an entry entered
then set stock +1
See below for my attempt, not sure if i need a join here?
update title_platform
set Stock = case
when tp_rental.Date_Returned is not null then stock -1
else stock +1
end
Am I going about this the right way?
You need an UPDATE statement with a join between the 2 tables and a CASE expression:
update title_platform p inner join tp_rental r
on r.platformid = p.platformid
set p.stock = p.stock + case
when r.date_due is not null and r.date_returned is null then -1
when r.date_due is not null and r.date_returned is not null then 1
else ? -- if there is another option
end
Remove the else part if it is not needed.
Edit: if there are multiple rows in tp_rental for each platformid then you must aggregate first and then join:
update title_platform p inner join (
select platformid,
sum(date_due is not null and date_returned is not null) -
sum(date_due is not null and date_returned is null) result
from tp_rental
group by platformid
) r on r.platformid = p.platformid
set p.stock = case
when p.stock + r.result < 0 then 0
else p.stock + r.result
end

Multiplying CASE row with different values

I'm creating a rating system. I have two tables hinne (rating) and hinnang (rating multiplier). I need to multiply the rating and then average the rating to know what rating I got out of all ratings by aine(subject).
Example:
All points need to be calculated in 0-100 point system.
So if my first rate is 25 and the rating multiplier is 4 then first rate (25/25)
4*25=100
If the second rate is 30 and multiplier 2 then second rate (30/50)
2*30=60
Now I need to average them like 100+60/2=80.
That should work in my SQL statement, but I got in trouble.
CASE
WHEN aine.nimetus = 'Füüsika I'
THEN hinne.tulemus * hindamine.kaal
ELSE 0
END
,0)
))
So, this is my pivot case statement. hindamine.kaal should be different value for each hinne.tulemus 25*4,50*2 BUT it doesn't work. It just uses multiplier value 4. How can I make this work?
The result of SQL: 150
The expected result: 100
Therefore here is my full SQL:
SELECT
tudeng.m_number,hindamine.kaal, ROUND(AVG(NULLIF(
CASE
WHEN aine.nimetus = 'Füüsika I'
THEN hinne.tulemus * hindamine.kaal
ELSE 0
END
,0)
))
AS FüüsikaI ,ROUND(AVG(NULLIF(
CASE
WHEN aine.nimetus = 'Kõrgem matemaatika I'
THEN hinne.tulemus * hindamine.kaal
ELSE 0
END
,0)
))
AS KõrgemmatemaatikaI ,ROUND(AVG(NULLIF(
CASE
WHEN aine.nimetus = 'Raalprojekteerimine'
THEN hinne.tulemus * hindamine.kaal
ELSE 0
END
,0)
))
AS Raalprojekteerimine ,ROUND(AVG(NULLIF(
CASE
WHEN aine.nimetus = 'Tehniline graafika'
THEN hinne.tulemus * hindamine.kaal
ELSE 0
END
,0)
))
AS Tehnilinegraafika , ROUND(AVG(NULLIF(
CASE
WHEN aine.nimetus = 'Ettevõteluse alused'
THEN hinne.tulemus * hindamine.kaal
ELSE 0
END
,0)
))
AS Ettevõtelusealused
FROM
tudeng
INNER JOIN
aine_tudeng
ON
tudeng.tudeng_id = aine_tudeng.tudeng_id
INNER JOIN
aine
ON
aine.aine_id = aine_tudeng.aine_id
INNER JOIN
hinne
ON
hinne.aine_tudeng_id=aine_tudeng.aine_tudeng_id
INNER JOIN
hindamine
ON
hindamine.hindamine_id=aine_tudeng.aine_id
GROUP BY
tudeng.m_number
I suppose your error is here:
ON hindamine.hindamine_id = aine_tudeng.aine_id
A hindamine (assessment/rating?) is something different from an aine (subject?), so you are mistaken in joining on these IDs.
(I have used Google translator to help me with the meanings.)

SQL Server Row totals in pivot query

I am trying to make a row in the end of the result set that shows the totals.
My query is this:
SELECT
[ ] = ISNULL(CAST(GEN_idPaciente AS VARCHAR)+'-'+nombrePaciente, 'TOTAL'),
[2016-11-01] = MAX([2016-11-01]),
[2016-11-02] = MAX([2016-11-02]),
[2016-11-03] = MAX([2016-11-03]),
[2016-11-04] = MAX([2016-11-04]),
TOTAL = COUNT([2016-11-01]) + COUNT([2016-11-02]) + COUNT([2016-11-03]) + COUNT([2016-11-04])
FROM
(
SELECT GEN_Paciente.GEN_idPaciente,COALESCE(GEN_ape_paternoPaciente, '')+' '+COALESCE(GEN_ape_maternoPaciente, '')+' '+COALESCE(GEN_nombrePaciente, '') AS nombrePaciente,HOS_fechaCategorizacion,HOS_nivel_riesgoCategorizacion+CAST(HOS_nivel_dependenciaCategorizacion AS VARCHAR) as riesgoDependencia
FROM HOS_Categorizacion
INNER JOIN HOS_Hospitalizacion
ON HOS_Hospitalizacion.HOS_idHospitalizacion = HOS_Categorizacion.HOS_idHospitalizacion
INNER JOIN GEN_Paciente
ON GEN_Paciente.GEN_idPaciente = HOS_Hospitalizacion.GEN_idPaciente
WHERE HOS_nivel_riesgoCategorizacion IS NOT NULL
) src
PIVOT
(
MAX(riesgoDependencia)
for HOS_fechaCategorizacion in ([2016-11-01],[2016-11-02],[2016-11-03],[2016-11-04])
) p
GROUP BY
ROLLUP(CAST(GEN_idPaciente AS VARCHAR)+'-'+nombrePaciente)
This gives me this result:
But as you can see the totals for the rows are right but the totals for the columns are wrong because I am using MAX instead of COUNT, but I only need COUNT in the TOTAL row, the others have to be MAX, so I wrote this query:
SELECT
[ ] = ISNULL(CAST(GEN_idPaciente AS VARCHAR)+'-'+nombrePaciente, 'TOTAL'),
[2016-11-01] = CASE WHEN CAST(GEN_idPaciente AS VARCHAR)+'-'+nombrePaciente IS NOT NULL THEN MAX([2016-11-01]) ELSE COUNT([2016-11-01]) END,
[2016-11-02] = CASE WHEN CAST(GEN_idPaciente AS VARCHAR)+'-'+nombrePaciente IS NOT NULL THEN MAX([2016-11-02]) ELSE COUNT([2016-11-02]) END,
[2016-11-03] = CASE WHEN CAST(GEN_idPaciente AS VARCHAR)+'-'+nombrePaciente IS NOT NULL THEN MAX([2016-11-03]) ELSE COUNT([2016-11-03]) END,
[2016-11-04] = CASE WHEN CAST(GEN_idPaciente AS VARCHAR)+'-'+nombrePaciente IS NOT NULL THEN MAX([2016-11-04]) ELSE COUNT([2016-11-04]) END,
TOTAL = COUNT([2016-11-01]) + COUNT([2016-11-02]) + COUNT([2016-11-03]) + COUNT([2016-11-04])
FROM
(
SELECT GEN_Paciente.GEN_idPaciente,COALESCE(GEN_ape_paternoPaciente, '')+' '+COALESCE(GEN_ape_maternoPaciente, '')+' '+COALESCE(GEN_nombrePaciente, '') AS nombrePaciente,HOS_fechaCategorizacion,HOS_nivel_riesgoCategorizacion+CAST(HOS_nivel_dependenciaCategorizacion AS VARCHAR) as riesgoDependencia
FROM HOS_Categorizacion
INNER JOIN HOS_Hospitalizacion
ON HOS_Hospitalizacion.HOS_idHospitalizacion = HOS_Categorizacion.HOS_idHospitalizacion
INNER JOIN GEN_Paciente
ON GEN_Paciente.GEN_idPaciente = HOS_Hospitalizacion.GEN_idPaciente
WHERE HOS_nivel_riesgoCategorizacion IS NOT NULL
) src
PIVOT
(
MAX(riesgoDependencia)
for HOS_fechaCategorizacion in ([2016-11-01],[2016-11-02],[2016-11-03],[2016-11-04])
) p
GROUP BY
ROLLUP(CAST(GEN_idPaciente AS VARCHAR)+'-'+nombrePaciente)
But that is not working
Thanks for your help!!
If I understand this correctly you want to count all columns which are not null. In this case you should just look at the condition IS NULL and not at the actual value at all. Try this:
DECLARE #tbl TABLE(ID INT IDENTITY, val1 VARCHAR(100),val2 VARCHAR(100),val3 VARCHAR(100));
INSERT INTO #tbl VALUES
('row1_val1','row1_val2',NULL)
,('row2_val1','row2_val2','row2_val3')
,(NULL,'row2_val2',NULL)
,(NULL,NULL,'row2_val3')
,(NULL,NULL,NULL);
SELECT *
,CASE WHEN val1 IS NULL THEN 0 ELSE 1 END
+CASE WHEN val2 IS NULL THEN 0 ELSE 1 END
+CASE WHEN val3 IS NULL THEN 0 ELSE 1 END AS CountOfValNotNull
FROM #tbl
UPDATE: Add a final Totals Row
You'd need ugly fiddling with a CTE, an additional sort column, UNION ALL to add another row and a sub_select.
Use the outer-most ORDER BY to get the artificial Totals-Row to the end
hint: Use the #tbl variable from above!
WITH SortedRows AS
(
SELECT ROW_NUMBER() OVER(ORDER BY ID) AS SortColumn
,*
,CASE WHEN val1 IS NULL THEN 0 ELSE 1 END
+CASE WHEN val2 IS NULL THEN 0 ELSE 1 END
+CASE WHEN val3 IS NULL THEN 0 ELSE 1 END AS CountOfValNotNull
FROM #tbl
)
SELECT tbl1.*
FROM
(
SELECT * FROM SortedRows
UNION ALL
SELECT 999999,0,'','','',(SELECT SUM(CountOfValNotNull) FROM SortedRows)
) AS tbl1
ORDER BY tbl1.SortColumn

MySQL Query Case

This is my code, i have 2 columns - Modem = String, Total = Integer
SELECT `Modem`, `Total`,
CASE `Modem` WHEN 'Yes' THEN
(`Total`+ 50)
ELSE
(`Total`+ 0)
END AS ModemAndTotal
FROM invoices
I need when Modem = "Yes" add 50 to total (Total + 50)
Try something like:
SELECT `Modem`, `Total`, CASE WHEN `Modem` = 'Yes' THEN (`Total`+ 50)
ELSE
`Total`
END AS ModemAndTotal
FROM invoices

Left join in complicated sql query

Hi guys i have this query
SELECT currency_code, SUM(
CASE
WHEN TYPE = 'cash_in'
THEN amount
END ) AS cash_in, SUM(
CASE
WHEN TYPE = 'cash_out'
THEN amount
END ) AS cash_out, SUM(
CASE
WHEN TYPE = 'cash_in'
THEN amount
ELSE - amount
END ) AS balance
FROM tb_cash_transaction
LEFT JOIN tb_currency ON tb_currency.CURRENCY_ID = tb_cash_transaction.CURRENCY_ID
WHERE TYPE IN (
'cash_in', 'cash_out'
)
GROUP BY currency_code
That will output this:
The problem is the query dont display another currency_code KRW which dont have data in tb_cash_transaction. Example in tb_currency
How to solve this?
Try this
SELECT currency_code, SUM(
CASE
WHEN TYPE = 'cash_in'
THEN amount
END ) AS cash_in, SUM(
CASE
WHEN TYPE = 'cash_out'
THEN amount
END ) AS cash_out, SUM(
CASE
WHEN TYPE = 'cash_in'
THEN amount
ELSE - amount
END ) AS balance
FROM tb_currency
LEFT JOIN tb_cash_transaction ON tb_currency.CURRENCY_ID = tb_cash_transaction.CURRENCY_ID AND tb_cash_transaction.TYPE IN (
'cash_in', 'cash_out'
)
GROUP BY currency_code