【问题标题】:SUM of COUNTS MySQLMySQL 计数的总和
【发布时间】:2013-03-01 01:05:09
【问题描述】:

我有以下 sql 查询

 SELECT 
(SELECT count(cid) from A where uid=45 group by cid) as cats 
(SELECT count(cid) from A where uid=45) as cats_total

第一个子选择产生 4 行并计算每个 cid 中的项目数。第二个子选择只产生 1 行并计算项目总数。

我的问题在于第二个子选择。 SQL 产生错误,因为它们具有不同数量的行。是否可以进行调整,使第二个子选择有 4 行,或者第一个子选择产生的行数?

更新:让我用我需要制作的表格进一步澄清

+------+------------+
| cats | cats_total |
+------+------------+
|    2 |         17 |
|    5 |         17 |
|    1 |         17 |
|    9 |         17 |
+------+------------+

【问题讨论】:

    标签: mysql sql count sum


    【解决方案1】:

    替代,你可以使用UNION ALL

    SELECT SUM(totals) grandTotal
    FROM
    (
        SELECT count(cid) totals from A where uid=45 group by cid
        UNION ALL
        SELECT count(cid) totals from A where uid=45
    ) s
    

    【讨论】:

    • 你能再看看我的澄清(我添加了一个表格),我尝试了你的方法,但我只得到了一行。感谢您的帮助。
    • 你能提供样本记录吗?
    • 你不需要一个例子就可以看出你的建议显然没有意义。它实际上返回了两倍的总数 count(cid)(其中 uid=45)。我猜你的意思是别的。
    【解决方案2】:

    卡夫是对的。

    如果有人对这里感兴趣的是通过 jdbc 测试到 Oracle db 的工作版本:

    SELECT cats,cats_total from  
    (SELECT count(cid) as cats from A where uid=45 group by cid)
    cross join
    (SELECT count(cid) as cats_total from A where uid=45)
    

    【讨论】:

      【解决方案3】:

      你可以试试

      SELECT cats.total, cats_total.total from 
      (SELECT count(cid) as total from A where uid=45 group by cid) as cats ,
      (SELECT count(cid) as total from A where uid=45) as cats_total
      

      【讨论】:

        【解决方案4】:

        我认为您可以对两个子查询进行交叉连接;

        SELECT cats, cats_total 
        FROM (SELECT count(cid) as cats from A where uid=45 group by cid) as c1 
                CROSS JOIN
             (SELECT count(cid) as cats_total from A where uid=45) as c2
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-02-14
          • 2016-08-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-05-26
          • 2012-04-04
          • 1970-01-01
          相关资源
          最近更新 更多