【问题标题】:SQL Count from INNER JOIN来自 INNER JOIN 的 SQL 计数
【发布时间】:2012-05-06 23:39:05
【问题描述】:

如何通过分组从内部联接中选择计数?

SELECT COUNT(table1.act) FROM table1
INNER JOIN table2 ON table1.act = table2.act
GROUP BY table1.act

这将返回在 table2 中找到的行为计数。

添加

 SELECT table1.act, COUNT(table1.act) AS test

返回

act     test
------- ----
17682   3
17679   3
17677   3
11636   1
11505   1

我想收到发现的行为总数。

所以我想得到 5 个。你能帮忙吗?

【问题讨论】:

    标签: sql count


    【解决方案1】:

    您可以将该查询包装到另一个查询中:

    SELECT COUNT(*) FROM (
        SELECT COUNT(table1.act) AS actCount FROM table1
        INNER JOIN table2 ON table1.act = table2.act
        GROUP BY table1.act
    ) t
    

    【讨论】:

    • 请注意,这会有点慢,但适用于您实际拥有的任何查询。如果就这么简单,请注意您只是在计算在 table2.act 中匹配的不同 table1.act
    • 我正在做的事情足够快。查询耗时 0.0142 秒。再次感谢!
    【解决方案2】:

    使用count distinct

    SELECT COUNT(distinct table1.act) FROM table1
    INNER JOIN table2 ON table1.act = table2.act
    

    【讨论】:

    • 我也试过了。那回来了。行为测试 -------- ---- 17682 1 17679 2 17677 1 11636 1 11505 1
    • 这很奇怪。粘贴代码时一定发生了什么事。在 sqlfiddle 上查看这个工作演示 sqlfiddle.com/#!3/1ab86/1
    • 这不会返回所有不同的行为吗?
    【解决方案3】:
    SELECT COUNT(table2.act) FROM table1
    INNER JOIN table2 ON table1.act = table2.act
    

    【讨论】:

    • 我需要 GROUP BY,因为 table2 中有多个字段具有相同的行为。在上面的语句中会返回 11。
    【解决方案4】:

    如果你只想要结果计数,

    SELECT     COUNT(1)
    FROM       table1
    INNER JOIN table2 ON table1.act = table2.act
    GROUP BY   table1.act
    

    这应该给你

    【讨论】:

      【解决方案5】:

      使用 SELECT COUNT 语句包装整个查询,如 Mosty Mostacho 的答案所示,只是想用 as 语句发布此答案,因为通常最好返回带有列标题的结果。

      SELECT COUNT(*) as FilteredActs FROM (
          SELECT COUNT(table1.act) AS actCount FROM table1
          INNER JOIN table2 ON table1.act = table2.act
          GROUP BY table1.act
      ) T
      

      结果:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-12
        • 2021-12-30
        • 1970-01-01
        • 1970-01-01
        • 2018-03-09
        • 2013-07-01
        • 2013-07-19
        • 1970-01-01
        相关资源
        最近更新 更多