使用聚合计算sql

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

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

  1. +-----+-----------------+-------+
  2. | CCA | NUMERO | STATO |
  3. +-----+-----------------+-------+
  4. | 057 | 007030020004527 | 0 |
  5. | 057 | 007030020004527 | 1 |
  6. | 057 | 007030020004527 | 1 |
  7. | 057 | 007030020004123 | 1 |
  8. | 057 | 007030020004123 | 1 |
  9. | 057 | 007030020001111 | 1 |
  10. | 057 | 007030020001111 | 1 |
  11. | 057 | 007030020001111 | 1 |
  12. +-----+-----------------+-------+

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

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

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

gev0vcfq

gev0vcfq1#

您需要两个级别的聚合:

  1. select t.cca, count(*) counter
  2. from (
  3. select cca, numero
  4. from tablename
  5. group by cca, numero
  6. having count(*) = sum(stato) -- or having min(stato) = 1
  7. ) t
  8. group by t.cca

请看演示。
或与 NOT EXISTS :

  1. select cca, count(distinct numero) counter
  2. from tablename t
  3. where not exists (
  4. select 1
  5. from tablename
  6. where cca = t.cca and numero = t.numero and stato = 0
  7. )
  8. group by cca

请看演示。
结果:

  1. | cca | counter |
  2. | --- | ------- |
  3. | 57 | 2 |
展开查看全部
h5qlskok

h5qlskok2#

你似乎想要:

  1. select cca
  2. from sinistro
  3. group by cca
  4. having count(*) = sum(stato);

相关问题