How can I simplify this mysql query, based on 2 tables? - mysql

after 2 days of trial and error, I just completed this mysql query. It works fine, but it does look really hideous. Is it possible to simplify my query ? All help is of course greatly appreciated.
SELECT
p.*,
COUNT(oT.Ontmoeting_ID) + COUNT(oU.Ontmoeting_ID) AS 'played',
COUNT(case oT.Ontmoeting_Uitploeg_FF when 1 then 1 else case oT.Ontmoeting_Thuisploeg_Bonus when 3 then 1 else null end end)
+ COUNT(case oU.Ontmoeting_Thuisploeg_FF when 1 then 1 else case oU.Ontmoeting_Uitploeg_Bonus when 3 then 1 else null end end)
- COUNT(case oU.Ontmoeting_Thuisploeg_FF when 1 then case oU.Ontmoeting_Uitploeg_FF when 1 then 1 else null end end)
- COUNT(case oT.Ontmoeting_Uitploeg_FF when 1 then case oT.Ontmoeting_Thuisploeg_FF when 1 then 1 else null end end) AS 'won',
COUNT(case oT.Ontmoeting_Thuisploeg_Bonus when 1 then 1 else null end) +
COUNT(case oU.Ontmoeting_Uitploeg_Bonus when 1 then 1 else null end) AS 'draw',
COUNT(case oU.Ontmoeting_Uitploeg_FF when 1 then 1 else case oU.Ontmoeting_Uitploeg_Bonus when 0 then 1 else null end end)
+ COUNT(case oT.Ontmoeting_Thuisploeg_FF when 1 then 1 else case oT.Ontmoeting_Thuisploeg_Bonus when 0 then 1 else null end end) AS 'lost',
SUM(COALESCE(oT.Ontmoeting_Thuisploeg_Totaal, 0)) + SUM(COALESCE(oU.Ontmoeting_Uitploeg_Totaal, 0)) AS 'Totaal'
FROM ploegen AS p
LEFT OUTER JOIN ontmoetingen AS oT ON oT.Ontmoeting_Thuisploeg_ID = p.Ploeg_ID AND oT.Ontmoeting_Competitie_ID = 1 and oT.Ontmoeting_Speelweek <= 2 AND (oT.Ontmoeting_Thuisploeg_Totaal > 0 OR oT.Ontmoeting_Thuisploeg_FF = 1)
LEFT OUTER JOIN ontmoetingen AS oU ON oU.Ontmoeting_Uitploeg_ID = p.Ploeg_ID and oU.Ontmoeting_Competitie_ID = 1 AND oU.Ontmoeting_Speelweek <= 2 AND (oU.Ontmoeting_Uitploeg_Totaal > 0 OR oU.Ontmoeting_Uitploeg_FF = 1)WHERE p.Ploeg_ID IN (select Ontmoeting_Thuisploeg_ID from ontmoetingen WHERE Ontmoeting_Competitie_ID = 1)
GROUP BY p.Ploeg_ID
ORDER BY totaal DESC
The query is based on 2 tables, "ontmoetingen" and "ploegen" (in English: "encounters" and "teams"). It calculates the overall standings of the teams, adding all played, won and draw encounters. The main difficulty is that all teams play both home and away games and those have to be summarized ("Thuisploeg" = "Home Team", "Uitploeg" = "Away Team". Please let me know if more info on the tables is required to help me out. Thx !
Table: "Ontmoetingen":
Table: "ploegen":
Expected output:
All numbers in output are fictional, so not corresponding to table data. Hope this helps !

Related

Why are my various CASE WHEN functions returning the same values?

Im trying to write a query that returns a count depending on the value of a feedback field that ranges from 0-5 (0 meaning that it was not rated).
I want:
Count of all rows ( anything rated 1 or greater)
Count of all rows rated as 1 (anything = 1)
And all rows rated as 1 and also is the first iteration of a given task (anything rated =1 and iteration = 0)
I have written this query but I am getting the same value for all counts:
select
DATE_FORMAT(created_at,'%M') as Month,
COUNT(CASE WHEN rate > 0 THEN 1 ELSE 0 END) AS total,
COUNT(CASE WHEN rate = 1 THEN 1 ELSE 0 END) AS Rated_1,
COUNT(CASE WHEN client_feedback = 1 AND index = 0 THEN 1 ELSE 0 END) AS first_iteration_rated_1
from tablexxx
where created_at between date('2022-04-01') and date('2022-10-01')
GROUP BY Month
Try to use SUM() instead of COUNT().
Count() will count up regardless of the value being 0 or 1.
you can have two approaches:
method 1: use NULL in else part of the CASE
select
DATE_FORMAT(created_at,'%M') as Month,
COUNT(CASE WHEN rate > 0 THEN 1 ELSE null END) AS total,
COUNT(CASE WHEN rate = 1 THEN 1 ELSE null END) AS Rated_1,
COUNT(CASE WHEN client_feedback = 1 AND index = 0 THEN 1 ELSE null END) AS first_iteration_rated_1
from tablexxx
where created_at between date('2022-04-01') and date('2022-10-01')
GROUP BY Month
method 2: use sum instead of count
select
DATE_FORMAT(created_at,'%M') as Month,
SUM(CASE WHEN rate > 0 THEN 1 ELSE 0 END) AS total,
SUM(CASE WHEN rate = 1 THEN 1 ELSE 0 END) AS Rated_1,
SUM(CASE WHEN client_feedback = 1 AND index = 0 THEN 1 ELSE 0 END) AS first_iteration_rated_1
from tablexxx
where created_at between date('2022-04-01') and date('2022-10-01')
GROUP BY Month

Distinct Count Query

I have a table below:
Item Status1 Status2
-----------------------------
A Good NULL
A Good NULL
A Good NULL
A Bad Good
B Bad Good
B Good NULL
C Good NULL
C Good NULL
C Good NULL
D Bad Good
Now, I'm thinking off writing a query which gives me the result below:
Item Good Bad
-----------------------------
A 4 1
B 2 1
C 3 0
D 1 1
Distinct in the Item column and the count of Good and Bad for each Item where NULL is not counted.
The column name can be of anything (I just kept it as Good and Bad in my second table).
Any suggestions/ideas on how to achieve my desired results?
Use UNION ALL & do aggregation :
select item, sum(status = 'good'), sum(status = 'bad')
from (select item, status1 as status
from table t
union all
select item, status2
from table t
) t
group by item;
You can use union all and conditional aggregation
select item, count(case when status1='good' then 1 end) as good,
count(case when status1='bad' then 1 end) as bad
from
(
select item , status1 from tablename
union all
select item , status2 from tablename
)A group by item
use union and case when
select Item, sum(case when status = 'good' then 1 else 0 end) as good,
sum ( case when status = 'bad' then 1 else 0 end) as bad
from (select Item, Status1 as status
from table_name
union all
select Item, Status2
from table_name
) t
group by Item;
There's no need for UNION, simply apply some logic.
select Item
,sum(case when Status1 = 'Good' then 1 else 0 end +
case when Status2 = 'Good' then 1 else 0 end) as good
,sum(case when Status1 = 'Bad' then 1 else 0 end +
case when Status2 = 'Bad' then 1 else 0 end) as bad
from tab
group by Item
or
select Item
,count(case when Status1 = 'Good' then 1 end) +
count(case when Status2 = 'Good' then 1 end) as good
,count(case when Status1 = 'Bad' then 1 end) +
count(case when Status2 = 'Bad' then 1 end) as good
from tab
group by Item
You can use sub-query and then apply sum function in outer query
select distinct(item) as item, sum(S1G+S2G) as Good,sum(S1B+S2B) as Bad from ( select item, CASE WHEN status1 ='Good' THEN 1 ELSE 0 END as S1G, CASE WHEN status2 ='Good' THEN 1 ELSE 0 END as S2G, CASE WHEN status2 ='Bad' THEN 1 ELSE 0 END as S2B, CASE WHEN status1 ='Bad' THEN 1 ELSE 0 END as S1B from t1 ) as b group by item
Here is demo

SUM CASE adding from joined table instead main table

I have a query that retrieves from a customer:
sum of time expent on his tickets (every ticket can have 1 or more interventions)
average resolution time
category of each ticket
The query:
SELECT SUM(f.duree) as total_time, SUM(timestampdiff(second, t.datec, t.date_close))/COUNT(distinct t.rowid) as average_resolution, COUNT(distinct t.rowid) as tickets,
SUM( CASE t.category_code WHEN 'WITHOUT_MAINTENANCE' THEN 1 ELSE 0 END) as sin_mantenimiento,
SUM( CASE t.category_code WHEN 'WITH_MAINTENANCE' THEN 1 ELSE 0 END) as con_mantenimiento,
SUM( CASE t.category_code WHEN 'WITH_BILLABLE_MAINTENANCE' THEN 1 ELSE 0 END) as con_mantenimiento_facturable,
SUM( CASE t.category_code WHEN 'NO_BILLABLE_COASER_WARRANTY' THEN 1 ELSE 0 END) as no_facturable_garantia_coaser,
SUM( CASE t.category_code WHEN 'OFERTADO' THEN 1 ELSE 0 END) as ofertado
FROM llx_ticketsup as t
JOIN llx_element_element as ee on ee.fk_source = t.rowid
JOIN llx_fichinter as f on f.rowid = ee.fk_target
WHERE t.fk_soc = 47 AND t.fk_statut = 8
where
llx_ticketsup is main tickets table
llx_fichinter is table where interventions from tickets are stored
llx_element_element is table between tickets and interventions
My problem is, if one ticket has more than 1 intervention, on sum of category types to know how many are from this category and how many from the other, it sums interventions instead tickets. For example, if query returns 2 tickets and they have a total of 6 interventions, it returns 6 tickets of category WITHOUT_MAINTENANCE, instead 2 tickets of category WITHOUT_MAINTENANCE.
Whats wrong? Thanks.
Nothings 'wrong' that's expected behaviour try using a sub query to get the duration. Something like
SELECT (select sum(f.duree) from llx_fichinter as f on f.rowid = ee.fk_target) as total_time, SUM(timestampdiff(second, t.datec, t.date_close))/COUNT(distinct t.rowid) as average_resolution, COUNT(distinct t.rowid) as tickets,
SUM( CASE t.category_code WHEN 'WITHOUT_MAINTENANCE' THEN 1 ELSE 0 END) as sin_mantenimiento,
SUM( CASE t.category_code WHEN 'WITH_MAINTENANCE' THEN 1 ELSE 0 END) as con_mantenimiento,
SUM( CASE t.category_code WHEN 'WITH_BILLABLE_MAINTENANCE' THEN 1 ELSE 0 END) as con_mantenimiento_facturable,
SUM( CASE t.category_code WHEN 'NO_BILLABLE_COASER_WARRANTY' THEN 1 ELSE 0 END) as no_facturable_garantia_coaser,
SUM( CASE t.category_code WHEN 'OFERTADO' THEN 1 ELSE 0 END) as ofertado
FROM llx_ticketsup as t
JOIN llx_element_element as ee on ee.fk_source = t.rowid
WHERE t.fk_soc = 47 AND t.fk_statut = 8
If that doesn't work add sample data and expected result to the question as text so we can play with it.

COUNT data using case when with mysql

SELECT NAMA_DUN,
COUNT(case when ((RIGHT(noMyKid, 1))% 2) = 0 then 1 else 0 end) AS FEMALE,
COUNT(case when ((RIGHT(noMyKid, 1))% 2) = 1 then 1 else 0 end) AS MALE,
COUNT(DISTINCT(noMyKid)) as jumlah
FROM mohon
LEFT JOIN dun ON dun.KOD_DUN=mohon.dun_nama
WHERE status_proses = 'diproses'
AND concat('20', substr(noMyKid, 1, 2)) = '2008'
AND status_mohon = 'Layak'
AND status_semak = '1'
AND (
status_bayar = ''
OR status_bayar = 'Belum'
OR status_bayar = 'Sudah')
AND (
status_terima = ''
OR status_terima = 'Terima'
) GROUP BY dun_nama
ORDER BY NAMA_DUN
This is my mysql code. why is my 'COUNT CASE WHEN' give the same output for female and male column.
Usually COUNT() is used to count rows and is therefore very often used in the form COUNT(*). When you use a field (or anything else) as a parameter into the COUNT() it counts 1 for every no NULL value.
In your case all your values are not NULL (they are either 1 or 0) and consequently you end up with the same results.
So Abhik Chakraborty is right, use SUM() and everything should be fine.
The COUNT() function does only recognize non-null values, so when using case expressions such as you have here, you can explicitly return NULL where needed
SELECT NAMA_DUN,
COUNT(case when ((RIGHT(noMyKid, 1))% 2) = 0 then 1 else NULL end) AS FEMALE,
COUNT(case when ((RIGHT(noMyKid, 1))% 2) = 1 then 1 else NULL end) AS MALE,
COUNT(DISTINCT(noMyKid)) as jumlah
OR, implicitly return NULL by ignoring the else condition
SELECT NAMA_DUN,
COUNT(case when ((RIGHT(noMyKid, 1))% 2) = 0 then 1 end) AS FEMALE,
COUNT(case when ((RIGHT(noMyKid, 1))% 2) = 1 then 1 end) AS MALE,
COUNT(DISTINCT(noMyKid)) as jumlah
OR, mimic the effect of count by using SUM() provided you do use 1 and 0 (or 1 and NULL)
SELECT NAMA_DUN,
SUM(case when ((RIGHT(noMyKid, 1))% 2) = 0 then 1 else 0 end) AS FEMALE,
SUM(case when ((RIGHT(noMyKid, 1))% 2) = 1 then 1 else 0 end) AS MALE,
COUNT(DISTINCT(noMyKid)) as jumlah

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;