繁体   English   中英

计算具有一个值的行数和具有另一个值的行数,并输出表中出现的最低值

[英]Count number of rows with one value and rows with another value, and output lowest appearing value in table

我想知道是否有可能计算MySQL表中包含pet列中的Cat值的行数,并计算同一表中包含pet列中的Dog值的表的行数。 并比较每个查询返回的行数,如果包含Cat的行少于包含“ Dog”的行,则输出“ Cat”,反之亦然。

编辑:这是我想要的一个例子。

$pet = mysql_query("SELECT squad, COUNT(pet) FROM mytable WHERE pet IN ('cat', 'dog', 'horse', 'snake') GROUP BY pet ORDER BY COUNT(pet) DESC LIMIT 1") or die(mysql_error());
echo $pet; // this should output the pet with the lowest number of rows

因此,它应该根据猫的行数最少来回响猫,狗,马或蛇。

您可以使用mysql中的COUNT()函数定义地执行此操作,并让php比较这些值。

SELECT pet, COUNT(pet)
FROM yourtable
WHERE pet IN ('Dog', 'Cat')
GROUP BY pet
select case 
        when CatCount > DogCount then 'Cat' 
        when CatCount < DogCount then 'Dog'
    end 
from (
    select count(case when pet = 'Cat' then 1 end) as CatCount,
        count(case when pet = 'Dog' then 1 end) as DogCount
    from MyTable
) a

pets表中选择猫和狗,将它们分组并计算每组的成员。 然后选择顶部组。

SELECT pet, COUNT(pet)
FROM pets
WHERE pet IN ('Cat', 'Dog')
GROUP BY pet
ORDER BY COUNT(pet)
LIMIT 1

这可以轻松扩展到更多类型的宠物。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM