Using CASE statement in SUM() In Stored Procedure - mysql

Here is my code:
BEGIN
SELECT SUM(
CASE WHEN first_name > '' THEN 1 ELSE 0 END AS a
CASE WHEN last_name > '' THEN 1 ELSE 0 END AS b,
CASE WHEN country > '' THEN 1 ELSE 0 END AS c,
CASE WHEN state > '' THEN 1 ELSE 0 END AS d,
CASE WHEN city > '' THEN 1 ELSE 0 END AS e)
AS total
FROM employee_profile
WHERE id = user_id_in;
END
This generates the following error:
you have an error in your SQL syntax check the manual that corresponds to your MySQL server version for the right syntax to use near xxx error for the first line.
Can anyone help with the correct syntax for this, please?
MySQL Server version: 5.5.8

SUM takes a single argument (/ column) which it sums across multiple rows, not multiple arguments (/ columns) for a single row, this is why it's not working.
This should work:
SELECT (CASE WHEN first_name > '' THEN 1 ELSE 0 END +
CASE WHEN last_name > '' THEN 1 ELSE 0 END +
CASE WHEN country > '' THEN 1 ELSE 0 END +
CASE WHEN state > '' THEN 1 ELSE 0 END +
CASE WHEN city > '' THEN 1 ELSE 0 END) AS total
FROM employee_profile
WHERE id = user_id_in;

Try this query this will suerly help you..
SELECT SUM(
CASE
WHEN first_name = '' THEN '1'
WHEN last_name = '' THEN '1'
WHEN country = '' THEN '1'
WHEN state = '' THEN '1'
ELSE '0'
END) AS total
FROM employee_profile
WHERE id = user_id_in;

Related

MySql select statement with conditional where clause

I am trying to write a MySql statement with a conditional where clause.
something like this:
set #price = 5000 ;
set #city = 1324368075;
select count(*)
from property
where case when #price is not null then
price < #price
end
and (case when #city is not null then
CityId = #city
end)
the variable should be included in the query only if it is not null.
My attempts have failed so far. Any ideas?
Edited:
Sorry I spoke too soon ysth,
these two queries are supposed to yield the same count but they dont.
Edit #2: Execution plan & indexes
Here's the query:
set #CountryId = null ;
set #CityId = 1324368075 ;
set #StateProvince = null ;
set #CategoryId = null ;
set #TransactionTypeId = null;
set #Price = 5000;
SELECT
Count(*)
FROM
meerkat.property
WHERE
(CASE WHEN #CountryId IS NOT NULL THEN CountryId = #CountryId ELSE 1 END)
AND (CASE WHEN #CityId IS NOT NULL THEN CityId = #CityId ELSE 1 END)
AND (CASE WHEN #CategoryId IS NOT NULL THEN CategoryId = #CategoryId ELSE 1 END)
AND (CASE WHEN #StateProvince IS NOT NULL THEN StateProvince = #StateProvince ELSE 1 END)
AND (CASE WHEN #TransactionTypeId IS NOT NULL THEN TransactionTypeId = #TransactionTypeId ELSE 1 END)
AND (CASE WHEN #Price IS NOT NULL THEN Price <= #Price ELSE 1 END)
AND IsPublic = 1
AND IsBlocked = 0;
Thanks in advance
If no when conditions are met, case returns null. If you want each test to pass, you need to return a true value instead, so:
case when #price is not null then
price < #price
else 1 end
and ...

MySQL SUM with CASE choose latest record by date

I've got the SUM CASE statements working properly. The issue is that I have multiple records with similar criteria, so I'd like to select the latest record by date.
SELECT
SUM(CASE WHEN planning like 'Rotation%' THEN 1 ELSE 0 END +
CASE WHEN assessmentanddata like 'Collects%' THEN 1 else 0 END +
CASE WHEN path like 'Same%' THEN 1 else 0 END +
CASE WHEN place like 'Move%' THEN 1 else 0 END +
CASE WHEN pace like 'Timer%' THEN 1 else 0 END +
CASE WHEN classroommanagement like 'Restating%' THEN 1 else 0 END +
CASE WHEN teacherrole like 'Mini%' THEN 1 else 0 END +
CASE WHEN studentengagement like 'Follow%' THEN 1 else 0 END +
CASE WHEN studentcollaboration like 'Collects%' THEN 1 else 0 END +
CASE WHEN technology like 'Technology%' THEN 1 else 0 END) AS p1
from ruberic where schoolId = 1
A sample from the table will be these 3 columns of DATE, SCHOOLID, and TEACHERID:
2016-12-05 1 1 -> This record will be fine
2016-12-05 1 4 -> Select only this when compared with the record below
2016-12-05 1 4
Building on what I see (I don't see the field name for date so assumed date)
This uses a correlates subquery and an exists statement to identify the max(date) for each teacherID and school and then limits the main dataset by this subset through the coloration.
SELECT
SUM(CASE WHEN planning like 'Rotation%' THEN 1 ELSE 0 END +
CASE WHEN assessmentanddata like 'Collects%' THEN 1 else 0 END +
CASE WHEN path like 'Same%' THEN 1 else 0 END +
CASE WHEN place like 'Move%' THEN 1 else 0 END +
CASE WHEN pace like 'Timer%' THEN 1 else 0 END +
CASE WHEN classroommanagement like 'Restating%' THEN 1 else 0 END +
CASE WHEN teacherrole like 'Mini%' THEN 1 else 0 END +
CASE WHEN studentengagement like 'Follow%' THEN 1 else 0 END +
CASE WHEN studentcollaboration like 'Collects%' THEN 1 else 0 END +
CASE WHEN technology like 'Technology%' THEN 1 else 0 END) AS p1
FROM
ruberic R1
WHERE
schoolId = 1
AND EXISTS (SELECT Null
FROM ruberic r2
WHERE R2.SchoolID = R1.SchoolID
AND R2.TeacherID = R1.TeacherID
GROUP BY SchoolID, TeacherID
HAVING R1.Date = MAX(R2.Date) )

PostgreSQL Error 22012 devided by Zero after Truncate The Table

So after I truncated my table, this query which worked before, now doesn't work. Even I've already filled again my table, It still doesn't work.
Here's my postgreSQL code :
SELECT
k.reviewer AS namareviewer
, COUNT(k.formcode) AS actual
, ROUND((0.2*COUNT(k.formcode))) AS target
, SUM(CASE WHEN k.blibliknowledge != '' THEN 1 ELSE 0 END) AS blibli
, COUNT(CASE WHEN k.solusi != '' THEN 'foo' ELSE NULL END) AS solusi
, ROUND(((COUNT(CASE WHEN k.solusi != '' THEN 'foo' ELSE NULL END)+ SUM(CASE WHEN k.blibliknowledge != '' THEN 1 ELSE 0 END)) /ROUND((0.2*COUNT(k.formcode))))*100,2) as Percentage
FROM kpi k
GROUP
BY k.reviewer
And my KPI Table
That data are the same with the first data which the query already worked. Why The error SQL state : 22012 devided by zero come up after the first table truncated? Thankyou in advanced :D
Use NULLIF to avoid divide by zero error
....
, ROUND(((COUNT(CASE WHEN k.solusi != '' THEN 'foo' ELSE NULL END)+ SUM(CASE WHEN k.blibliknowledge != '' THEN 1 ELSE 0 END))
/NULLIF(ROUND((0.2*COUNT(k.formcode))))*100,2) ,0) as Percentage
........
Complete code :
SELECT
k.reviewer AS namareviewer,
COUNT(k.formcode) AS actual,
ROUND((0.2 * COUNT(k.formcode))) AS target,
SUM(CASE
WHEN k.blibliknowledge != '' THEN 1
ELSE 0
END) AS blibli,
COUNT(CASE
WHEN k.solusi != '' THEN 'foo'
ELSE NULL
END) AS solusi,
ROUND(((COUNT(CASE
WHEN k.solusi != '' THEN 'foo'
ELSE NULL
END) + SUM(
CASE
WHEN
k.blibliknowledge != '' THEN 1
ELSE 0
END)) / NULLIF(ROUND((
0.2 * COUNT(k.formcode))), 0)) * 100, 2) AS Percentage
FROM kpi k
GROUP BY k.reviewer

MySQL CASE WHEN where clause causes failure

I have a complex query that does multiple matches across multiple columns and then orders by relevance.
Everything works fine UNTIL I add WHERE 'rank' > 0
This then returns an empty results set.
If I remove the 'WHERE' statement then I can see all results with the highest matches at the top.
Could someone help me work out 'WHERE' :-D I am going wrong!!
SELECT *, CASE WHEN companyName = 'gfdgfs' THEN 2 ELSE 0 END
+ CASE WHEN companyName LIKE '%gfdgfs%' THEN 1 ELSE 0 END
+ CASE WHEN companyName = 'potato' THEN 2 ELSE 0 END
+ CASE WHEN companyName LIKE '%potato%' THEN 1 ELSE 0 END
+ CASE WHEN address1 = 'gfdgfs' THEN 2 ELSE 0 END
+ CASE WHEN address1 LIKE '%gfdgfs%' THEN 1 ELSE 0 END
+ CASE WHEN address1 = 'potato' THEN 2 ELSE 0 END
+ CASE WHEN address1 LIKE '%potato%' THEN 1 ELSE 0 END
AS rank
FROM clients
WHERE rank > 0
ORDER BY rank
EDIT
I removed the single quotes around the rank word and now get 'unknown column rank in where clause'
Remove single quotes from rank and try. Anyway, I don't think MySQL would support WHERE clause with aliases - check this.
Use HAVING rather than WHERE:
SELECT *, CASE WHEN companyName = 'gfdgfs' THEN 2 ELSE 0 END
+ CASE WHEN companyName LIKE '%gfdgfs%' THEN 1 ELSE 0 END
+ CASE WHEN companyName = 'potato' THEN 2 ELSE 0 END
+ CASE WHEN companyName LIKE '%potato%' THEN 1 ELSE 0 END
+ CASE WHEN address1 = 'gfdgfs' THEN 2 ELSE 0 END
+ CASE WHEN address1 LIKE '%gfdgfs%' THEN 1 ELSE 0 END
+ CASE WHEN address1 = 'potato' THEN 2 ELSE 0 END
+ CASE WHEN address1 LIKE '%potato%' THEN 1 ELSE 0 END
AS rank
FROM clients
HAVING rank > 0
ORDER BY rank
Try this:
SELECT *
FROM (SELECT *, CASE WHEN companyName = 'gfdgfs' THEN 2 ELSE 0 END
+ CASE WHEN companyName LIKE '%gfdgfs%' THEN 1 ELSE 0 END
+ CASE WHEN companyName = 'potato' THEN 2 ELSE 0 END
+ CASE WHEN companyName LIKE '%potato%' THEN 1 ELSE 0 END
+ CASE WHEN address1 = 'gfdgfs' THEN 2 ELSE 0 END
+ CASE WHEN address1 LIKE '%gfdgfs%' THEN 1 ELSE 0 END
+ CASE WHEN address1 = 'potato' THEN 2 ELSE 0 END
+ CASE WHEN address1 LIKE '%potato%' THEN 1 ELSE 0 END
AS rank
FROM clients
) AS A
WHERE rank > 0
ORDER BY rank;

Is it possible to use SUM - CASE - IF together?

When I try to use this:
SUM(CASE WHEN IF(SUM(CASE WHEN "b.count_students_status" = 1 THEN 1 ELSE 0 END) >= 1, 1, 0) = 1 THEN 1 ELSE 0 END)
It says Query Error: Improper usage of Group Function
Below is the complete code:
SELECT
"a.batch" AS Batch,
SUM(
CASE
WHEN IF(
SUM(
CASE
WHEN "b.count_students_status" = 1
THEN 1
ELSE 0
END
) >= 1,
1,
0
) = 1
THEN 1
ELSE 0
END
) AS Payments_Not_Received
FROM
"DBU - Complete"
WHERE "a.suspended" = 'no'
GROUP BY "a.batch"
I wanted to convert the status to 1, if there are multiple occurrences and then sum the total occurrences.
Any help please - I am using ZOHO to build the query?
You're trying to reference the result of the GROUP BY before is has run. Try something like this:
select t.BATCH,
sum(case when t.pnr >=1 then 1 else 0 end) as Payments_Not_Received
from
(
select
a.batch as BATCH,
SUM(CASE WHEN "b.count_students_status" = 1 THEN 1
ELSE 0
END) as pnr
from yourTable a
WHERE a.suspended = 'no'
group by a.batch
) t
group by t.BATCH;