这是在MySQL中。我创建了以下查询,该查询返回了我想要的答案,但是看起来很令人讨厌(并且可能比它可能要慢)。有办法简化吗?
select Status
, count(d.FruitType) as Count
, (select count(distinct FruitType) from Fruits) as TotalTypesOfFruit
from (select c.FruitType
, case
when sum(c.Eaten) > 4 then 'Popular'
else 'Not Popular'
end as Status
from (select a.*
, b.PieceID
, b.Size
, case
when b.Size > a.AvgSize then 1
else 0
end as Eaten
from Fruits a
left join Fruit_Pieces b
on a.FruitType = b.FruitType) c
group by c.FruitType) d
group by Status;
要实现此目的,我创建大量子查询只是为了进行计算,因此我可以在较大的子查询中使用该计算。必须有更好的方法。
编辑:
到目前为止,我已经对其进行了简化:
select Status
, count(c.FruitType) as Count
, (select count(distinct FruitType) from Fruits) as TotalTypesOfFruit
from (select a.FruitType
, case
when sum(
case
b.Size > a.AvgSize then 1
else 0
end) > 4 then 'Popular'
else 'Not Popular'
end as Status
from Fruits a
left join Fruit_Pieces b
on a.FruitType = b.FruitType
group by a.FruitType) c
group by Status
order by Status
似乎仍然不理想。它更具可读性,但似乎没有更快的速度。