使用LEFT JOIN,SUM()和HAVING()选择COUNT()

时间:2018-02-07 15:47:15

标签: mysql sql

我在这里有这张桌子 http://sqlfiddle.com/#!9/9d9f56/1/0

我不断获得超过单行的值4而不是我应该得到的实际COUNT(),这是3,即使我增加了分数至67COUNT4有多行,而不是一行。

我已添加SUM(b.score) AS score将其定义为variable,然后我首先使用HAVING score > 0来获取实际COUNT,如何解决此问题并获取一个COUNT行与实际计数?

我所期望的是包含实际分数>的单行。 0,这是3

我所做的是为每个SUM()获取scores name,使用N1获取id/nid = 1名称总得分{{1} },当我将(10)更改为score > 0时,我应该只获得一个值为score > 9的名称

> 9

所以     N1(nid=1) (b.score SUM=10), N2(nid=2) (b.score SUM=8), N3(nid=3) (b.score SUM=6) 应该给我HAVING score > 0COUNT(a.id) = 3应该给我HAVING score > 9

5 个答案:

答案 0 :(得分:2)

根据相关新信息进行修改:

这解释了原因:

select a.id, COUNT(*), SUM(b.score) AS score
FROM names a
LEFT JOIN scores b ON b.nid = a.id
GROUP BY a.id
HAVING score > 0

您正在对a.id进行分组,但由于您没有输出它,它看起来像重复。

这就是你需要的:

select COUNT(distinct a.id)
FROM names a
INNER JOIN scores b ON b.nid = a.id
WHERE score > 0

答案 1 :(得分:2)

使您的查询成为子查询并再次选择计数:

SElECT COUNT(score)
FROM (SELECT SUM(b.score) AS score
      FROM names a
      LEFT JOIN scores b ON b.nid = a.id
      GROUP BY a.id
      HAVING score > 0) s

这将根据您的要求为您提供值为3的单行。但是,您的查询可以简化,因为不需要连接:

SElECT COUNT(score)
FROM (SELECT SUM(score) AS score
      FROM scores
      GROUP BY nid
      HAVING score > 0) s

答案 2 :(得分:1)

如果您要查找谁score > 0然后计算,这可能会有所帮助:

select count(*) from 
    (select distinct nid 
     FROM scores
     where score > 0) as t

答案 3 :(得分:1)

尝试此查询:(PS:我在组中使用选择组,可能需要进一步调整才能获得最佳性能)。在where子句中有2个不同分数的查询。

select  
    count(*), ab.id  
from 
    (select   
         a.id, sum(b.score) as score 
     from
         names a
     left join
         scores b on a.id = b.nid
     group by
         a.id
     having 
         score > 0) ab

select 
    count(*), ab.id  
from  
    (select
         a.id, sum(b.score) as score 
     from
         names a
     left join
         scores b on a.id = b.nid
     group by
         a.id
     having
         score > 9) ab

答案 4 :(得分:1)

到目前为止,你所拥有的是一个很好的子查询:

SElECT COUNT(id) as idCount FROM (
  SELECT a.id, SUM(b.score) AS score FROM names a
  LEFT JOIN scores b ON b.nid = a.id
  GROUP BY a.id) ss
WHERE score> 9

您想要总分超过您要求的ID计数,此查询会给出您的分数级别的预期结果。

子查询给出:

+----+-------+
| id | score |
+----+-------+
|  1 |    10 |
|  2 |     8 |
|  3 |     6 |
+----+-------+

然后运行查询,只需在where子句中计算得分符合条件的ID。

SQLFiddle

更新 -

子查询中的连接实际上什么也没做,除了根据您提供的信息减慢执行速度。您可以删除联接,删除执行计划中的步骤并加快查询速度:

SElECT COUNT(id) as idCount FROM (
  SELECT nid as id, SUM(score) AS score FROM scores
  GROUP BY nid) ss
WHERE score> 9

SQLFiddle