【问题标题】:GROUP BY with multiple GROUPING SETS, CUBE, and ROLLUP clauses带有多个 GROUPING SETS、CUBE 和 ROLLUP 子句的 GROUP BY
【发布时间】:2015-12-24 09:54:16
【问题描述】:

今天我阅读了关于在 GROUP BY 子句中使用多个 GROUPING SETS、CUBE 和 ROLLUP 子句的提示。

您可以在中指定多个 GROUPING SETS、CUBE 和 ROLLUP 子句 用逗号分隔的 GROUP BY 子句。通过这样做,您可以实现 乘法效应。例如子句 CUBE(a, b, c) 定义 八个分组集和子句 ROLLUP(x, y, z) 定义了四个 分组集。通过在两者之间指定逗号,如 CUBE(a, b, c), ROLLUP(x, y, z),将它们相乘得到 32 个分组集。

这是一个例子。

SELECT
    shipcountry, GROUPING(shipcountry) AS grpcountry,
    shipcity , GROUPING(shipcity) AS shipcity,
    GROUPING_ID( shipcountry, shipcity ) AS grp_id,
    COUNT(*) AS numorders
FROM Sales.Orders
GROUP BY CUBE(shipcountry,shipcity), ROLLUP(shipcountry, shipcity)

我无法绕开它。问题是,结果集中有很多重复的行。如果我们将 DISTINCT 添加到 SELECT 子句中,即使没有 ROLLUP(shipcountry, shipcity),结果集也将是相同的。有什么意义?

【问题讨论】:

    标签: sql-server tsql group-by


    【解决方案1】:

    我认为当您为多维数据集和汇总子句指定不同的参数时,该实用程序就会出现。这在您引用的任何来源中都很明显。多维数据集和汇总中的每一个都只是更长的分组集列表的快捷方式。在您的示例中,多维数据集定义了以下分组集

    1. 船国,船城
    2. 船国
    3. 船城
    4. (空)

    而汇总指定了这些集合:

    1. 船国,船城
    2. 船国
    3. (空)

    当您在同一个 group by 子句中同时指定两者时,您会从第一个中获取每个集合,并从第二个中获取每个集合(这就是您的拉引号的乘法效应所暗示的)。所以你得到(使用命名法“(x)+(y)”来表示“第一组中的项目x和第二组中的项目y):

    1. (1) + (1) → (shipcountry, shipcity) + (shipcountry, shipcity) → (shipcountry, shipcity)
    2. (1) + (2) → (shipcountry, shipcity) + (shipcountry) → (shipcountry, shipcity)
    3. (1) + (3) → (shipcountry, shipcity) + ((null)) → (shipcountry, shipcity)
    4. (2) + (1) → (shipcountry) + (shipcountry, shipcity) → (shipcountry, shipcity)
    5. (2) + (2) → (shipcountry) + (shipcountry) → (shipcountry)
    6. (2) + (3) → (shipcountry) + ((null)) → (shipcountry)
    7. (3) + (1) → (shipcity) + (shipcountry, shipcity) → (shipcountry, shipcity)
    8. (3) + (2) → (shipcity) + (shipcountry) → (shipcountry, shipcity)
    9. (3) + (3) → (shipcity) + ((null)) → (shipcity)
    10. (4) + (1) → ((null)) + (shipcountry, shipcity) → (shipcountry, shipcity)
    11. (4) + (2) → ((null)) + (shipcountry) → (shipcountry)
    12. (4) + (3) → ((null)) + ((null)) → ((null))

    如您所见,有很多重复项。例如,(shipcountry, shipcity) 在 1、2、3、4、7、8 和 10 中出现 7 次。

    如果您为汇总和多维数据集指定不同的参数,您将获得一组完全不同的分组集。

    最后,记住我上面所说的:rollup 和 cube 都是常用的分组模式的快捷方式。如果您只需要某些分组集,请仅指定具有分组集子句的那些!

    【讨论】:

      猜你喜欢
      • 2014-10-06
      • 2016-11-20
      • 1970-01-01
      • 2016-05-14
      • 2021-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-11
      相关资源
      最近更新 更多