COUNTS的SUM

时间:2013-03-13 07:40:50

标签: mysql sql count sum

我有以下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 |
+------+------------+

4 个答案:

答案 0 :(得分:0)

另外,您可以使用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

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

Kaf是对的。

如果有人对这里感兴趣的是通过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 :(得分:0)

你可以尝试

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
相关问题