-1

我正在尝试理解一位同事编写的 SQL,但我正在努力理解 GROUPING() 函数在这种情况下是如何工作的。为什么最后两行中date_level_year_quarter_month的值等于 3 和 7?先感谢您!

SELECT
    t_year,
    t_quarter,
    t_month,
    GROUPING(t_year, t_quarter, t_month) date_level_year_quarter_month
FROM
    d_time
WHERE t_year IN (2016)
GROUP BY
ROLLUP(t_year, t_quarter, t_month)
ORDER BY 1, 2, 3;

+---------+------------+------------+-------------------------------+
| t_year  |  t_quarter |  t_month   | date_level_year_quarter_month |
+---------+------------+------------+-------------------------------+
| 2016    |      1     |      1     |               0               |
+---------+------------+------------+-------------------------------+
| 2016    |      1     |      2     |               0               |
+---------+------------+------------+-------------------------------+
| 2016    |      1     |      3     |               0               |
+---------+------------+------------+-------------------------------+
| 2016    |      1     |            |               1               |
+---------+------------+------------+-------------------------------+
| 2016    |    ...     |     ...    |              ...              |
+---------+------------+------------+-------------------------------+
| 2016    |            |            |               3               |
+---------+------------+------------+-------------------------------+
|         |            |            |               7               |
+---------+------------+------------+-------------------------------+

编辑:看起来对于“添加”的每个维度,GROUPING 函数的值是“先前分组”+ 1 值的两倍,但是我仍然不清楚该函数首先如何计算这些值。

SELECT 
      T_YEAR
    , T_QUARTAL
    , T_MONTH
    , T_WEEK
    , T_DATE
    , GROUPING (T_YEAR ) AS LEVEL_YEAR
    , GROUPING (T_YEAR, T_QUARTER) AS LEVEL_YEAR_QUARTAL
    , GROUPING (T_YEAR, T_QUARTER, T_MONTH) AS LEVEL_YEAR_QUARTAL_MONTH
    , GROUPING (T_YEAR, T_QUARTER, T_MONTH, T_WEEK) AS LEVEL_YEAR_QUARTAL_MONTH_WEEK
    , GROUPING (T_YEAR, T_QUARTER, T_MONTH, T_WEEK, T_DAY) AS LEVEL_YEAR_QUARTAL_MONTH_WEEK_DAY
FROM D_TIME
WHERE T_YEAR=2016 AND T_WEEK = 1
GROUP BY
ROLLUP (T_YEAR, T_QUARTER, T_MONTH, T_WEEK, T_DAY) 
ORDER BY 5,1,2,3,4;

分组输出:

4

1 回答 1

0

我在Exasol 文档中找到了答案。

“如果有多个参数,结果值是一个数字,其二进制表示类似于

GROUPING(arg1), GROUPING(arg2),..., GROUPING(argn). 

例如,以下情况为真:

GROUPING(a,b,c) = 4xGROUPING(a) + 2xGROUPING(b) + 1xGROUPING(c)."
于 2018-05-03T12:29:02.447 回答