GROUP BY...WITH ROLL UP 分组统计后的再合计

GROUP BY...WITH ROLL UP 是group by 的高配版,在group by 分组之后,再合计总数。

ex:求8月1号到9号每日投资人数  

SELECT
COUNT(DISTINCT investor_uid)AA,
FROM_UNIXTIME(add_time, '%Y-%m-%d')BB
FROM
lzh_borrow_investor
WHERE
FROM_UNIXTIME(add_time) BETWEEN '2016-8-1 00:00:00'
AND '2016-8-10 00:00:00'
GROUP BY
FROM_UNIXTIME(add_time, '%Y-%m-%d') WITH ROLLUP;

结果如下:

AA           BB

3 2016-08-01
1 2016-08-02
3 2016-08-03
4 2016-08-04
1 2016-08-05
1 2016-08-06
3 2016-08-07
6 2016-08-08
4 2016-08-09
25


很奇怪对不对,3+1+3+4+1+1+3+6+4!=25,这是因为distinct这个关键词。每日的投资人数和1-9号总投资人数是不同的,roll up 去重了。另外如果group by 了2个列,with rollup 也会分别统计第一个列,再统计两个列;举个网上找的例子:

SELECT  
      CASE WHEN (GROUPING(SEX) = 1) THEN '统计-ROLLUP' 
            ELSE ISNULL(SEX, 'UNKNOWN') 
       END AS SEX , 
      CASE WHEN (GROUPING([DEPARTMENT]) = 1) THEN '统计-ROLLUP' 
            ELSE ISNULL([DEPARTMENT], 'UNKNOWN') 
       END AS [DEPARTMENT], 
        COUNT(0) 
FROM DBO.[STAFF] 
GROUP BY   SEX,[DEPARTMENT]   WITH ROLLUP


与group by ...with rollup 孖生用法是  group by ...cube 二者都适用于sql server ,不过这个cube在mysql 中并不适用。

with cube 与with rollup的不同点在于:

使用 ROLLUP 会先统计分组下的,然后在对GROUP BY的第一列字段进行统计,最后计算总数,而 CUBE 则是先分组统计,然后统计GRUOP BY 的每个字段,最后进行汇总。

举个cube例子:

SELECT  
      CASE WHEN (GROUPING(SEX) = 1) THEN '统计-CUBE' 
            ELSE ISNULL(SEX, 'UNKNOWN') 
       END AS SEX ,
      CASE WHEN (GROUPING([DEPARTMENT]) = 1) THEN  '统计-CUBE' 
            ELSE ISNULL([DEPARTMENT], 'UNKNOWN') 
       END AS [DEPARTMENT], 
        COUNT(0) 
FROM DBO.[STAFF] 
GROUP BY   SEX,[DEPARTMENT]  WITH CUBE



你可能感兴趣的:(GROUP BY...WITH ROLL UP 分组统计后的再合计)