如何获取每个元素的计数和名称?

时间:2017-01-18 06:13:27

标签: mysql

我想从此查询的输出中获取总计数:

SELECT category as every, COUNT(*)
FROM categorydata
GROUP BY category

输出如下:

    every
--------------------------------------  
    TRAI-VPURA  68
    SCHO-VPURA  44
    TECH-BLORE  122
    REAL-VPURA  193
    BIZS-BLORE  2816
    HOSP-VPURA  30
    VIDYARANYAPURA  182
    PLAC-BLORE  461
    business    471
    COLL-VPURA  10
    SOFT-BLORE  362
    TIE-BLORE   95

我想获得总计数,即:3538 (as total)。我怎么能这样做?

3 个答案:

答案 0 :(得分:1)

您可以添加with rollup之类的

SELECT category as every, COUNT(*)
FROM categorydata
GROUP BY category
WITH ROLLUP

这将增加总额的额外记录。

修改
或者,如果你只是想要总和(没有小组结果)你当然可以简单地做

SELECT COUNT(*) FROM categorydata 

答案 1 :(得分:0)

 SELECT sum(tmpTable.every) as every from 
         (SELECT count(*) as every 
                 from categorydata 
           GROUP BY category) as tmpTable;

您不需要 GROUP BY 子句。它会产生相同的结果。

说明: parens中的代码只是创建一个临时表,只在名为每个的字段上,临时表在我的情况下需要命名为“tmpTable”。现在我们的查询变为选择sum(every)作为每个来自tmpTable tmpTable 是一个动态创建的临时表,其中包含单个字段名称每个,实际上是表格类别下的行数的 categorydata

答案 2 :(得分:-2)

试试这个:

SELECT sum(cnt)
FROM
  (SELECT category AS EVERY,
          COUNT(*) AS cnt
   FROM categorydata
   GROUP BY category) AS tmp;