使用聚合计算sql

nfg76nw0  于 2021-08-20  发布在  Java
关注(0)|答案(2)|浏览(317)

我无法计算某些条件下的记录。我就拿这张table为例

+-----+-----------------+-------+
| CCA |     NUMERO      | STATO |
+-----+-----------------+-------+
| 057 | 007030020004527 |     0 |
| 057 | 007030020004527 |     1 |
| 057 | 007030020004527 |     1 |
| 057 | 007030020004123 |     1 |
| 057 | 007030020004123 |     1 |
| 057 | 007030020001111 |     1 |
| 057 | 007030020001111 |     1 |
| 057 | 007030020001111 |     1 |
+-----+-----------------+-------+

我对这个例子的预期结果是
057 2
当count(numero)=sum(stato)时,我想为每个cca计算numero的数量,但我不能。我尝试了类似的方法,但结果不正确(表名为sinistro)

SELECT cca, count(numero) AS totali, sum(stato) as gestiti 
FROM `sinistro`
GROUP BY sinistro.cca
HAVING (totali - gestiti) = 0

我可以列出所有具有此条件的数字,但我无法计算它们。我总是不吵架。
我该怎么做?

gev0vcfq

gev0vcfq1#

您需要两个级别的聚合:

select t.cca, count(*) counter
from (
  select cca, numero
  from tablename
  group by cca, numero
  having count(*) = sum(stato) -- or having min(stato) = 1
) t
group by t.cca

请看演示。
或与 NOT EXISTS :

select cca, count(distinct numero) counter
from tablename t
where not exists (
  select 1 
  from tablename
  where cca = t.cca and numero = t.numero and stato = 0
)
group by cca

请看演示。
结果:

| cca | counter |
| --- | ------- |
| 57  | 2       |
h5qlskok

h5qlskok2#

你似乎想要:

select cca
from sinistro
group by cca
having count(*) = sum(stato);

相关问题