[英]how to count and select a max value of the count mysql
I have this code:我有这个代码:
select count(quantite) from lignescommandes where quantite ='1'
union
select count(quantite) from lignescommandes where quantite ='2'
union
select count(quantite) from lignescommandes where quantite ='3' ;
I want to select the highest value of the table that is returned but i don't see how to do that.我想 select 返回的表的最大值,但我不知道该怎么做。
Thanks in advance for your help在此先感谢您的帮助
You don't need UNION
.你不需要
UNION
。
You can do it in only 1 scan of the table with conditional aggregation and the function GREATEST()
:您只需使用条件聚合和 function
GREATEST()
对表进行 1 次扫描即可:
SELECT GREATEST(
COUNT(CASE WHEN quantite ='1' THEN quantite END),
COUNT(CASE WHEN quantite ='2' THEN quantite END),
COUNT(CASE WHEN quantite ='3' THEN quantite END)
) AS max_count
FROM lignescommandes
or with SUM()
instead of COUNT()
:或使用
SUM()
而不是COUNT()
:
SELECT GREATEST(
SUM(quantite ='1'),
SUM(quantite ='2'),
SUM(quantite ='3')
) AS max_count
FROM lignescommandes
select max(c)
from (
select count(quantite) as c from lignescommandes where quantite ='1'
union
select count(quantite) from lignescommandes where quantite ='2'
union
select count(quantite) from lignescommandes where quantite ='3'
) x
I would suggest:我会建议:
select count(*)
from lignescommandes
where quantite in ('1', '2', '3')
group by quantite
order by count(*) desc
limit 1;
In other words, you are basically replicating an aggregation query with union
which seems silly.换句话说,您基本上是在使用
union
复制一个聚合查询,这看起来很愚蠢。
Also, if quantite
(as its name implies) is a number, then drop the single quotes.此外,如果
quantite
(顾名思义)是一个数字,则去掉单引号。 Don't mix numbers and strings.不要混合数字和字符串。
And, if the only three values are 1
, 2
, and 3
, the where
clause is not needed at all.而且,如果只有三个值是
1
、 2
和3
,则根本不需要where
子句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.