簡體   English   中英

如何計數和 select 計數的最大值 mysql

[英]how to count and select a max value of the count mysql

我有這個代碼:

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' ;

我想 select 返回的表的最大值,但我不知道該怎么做。

在此先感謝您的幫助

你不需要UNION

您只需使用條件聚合和 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

或使用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

我會建議:

select count(*)
from lignescommandes
where quantite in ('1', '2', '3')
group by quantite
order by count(*) desc
limit 1;

換句話說,您基本上是在使用union復制一個聚合查詢,這看起來很愚蠢。

此外,如果quantite (顧名思義)是一個數字,則去掉單引號。 不要混合數字和字符串。

而且,如果只有三個值是123 ,則根本不需要where子句。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM