I have the following tables
Table Farm
+---------+--------+-------------------+-----------+------------+
| FARM_ID |Stock_ID| FARM_T
Here is the query I've been working on. However, the results are slighly different from the ones you've posted in your question:
select o.origin_name, s.stock_title, sum(
case f.size
when 'H' then
case
when sizes = 'H,L,M' then 70
when sizes = 'H,M' then 80
when sizes = 'H,L' then 90
when sizes = 'H' then 100
else 0
end
when 'M' then
case
when sizes = 'H,L,M' then 20
when sizes = 'H,M' then 20
when sizes = 'L,M' then 60
when sizes = 'M' then 100
else 0
end
else
case
when sizes = 'H,L,M' then 10
when sizes = 'L,M' then 40
when sizes = 'H,L' then 10
when sizes = 'L' then 100
else 0
end
end * r.score / 100) FinalScore
from farm f
join (
select f.stock_id, group_concat(distinct f.size order by f.size) sizes
from farm f
join results r on f.farm_id = r.farm_id
group by f.stock_id
) stockSizes on f.stock_id = stockSizes.stock_id
join results r on f.farm_id = r.farm_id
join (
select f.stock_id, r.gate_id
from results r
join farm f on r.farm_id = f.farm_id
group by f.stock_id, r.gate_id
having sum(r.score = 0) = 0
) FullGates
on FullGates.stock_id = f.stock_id and FullGates.gate_id = r.gate_id
join stock s on s.stock_id = f.stock_id
join origin o on o.origin_id = s.origin_id
group by o.origin_id, s.stock_id
Result:
+-------------+-------------+------------+ | ORIGIN_NAME | STOCK_TITLE | FINALSCORE | +-------------+-------------+------------+ | US | P1 | 93 | | CA | P3 | 90 | | MX | Q4 | 100 | | MX | B3 | 100 | +-------------+-------------+------------+
Let me know if this did the trick.
I would take your original query to get the second last table and change the Select
by adding use distinct
(found here) and only select Origin, Stock and the calculation for the Score. For example if the score is an average of all of them it would be AVG(Score)
where Score
would be what you fetched in the original query. If you want to use only a small subset of the items that have the same Origin and Stock to calculate the Score I would use a subquery, with the where matching the Origin and Stick ids, in the select so you have:
Select Origin,
Stock,
(select calculation(Score) from tables where tables.stock_id = .... tables.origin_id = .....)
From....
Hope this helps.