如何结合CUBE和ROLLUP?

时间:2014-05-23 12:32:03

标签: sql-server sql-server-2000

我有一个重要的GROUP BY聚合查询。这是一个简化的模式(SQL Fiddle):

CREATE TABLE [data] (
    [year] [int] NOT NULL ,
    [month] [int] NOT NULL ,
    [country] [varchar] (32) NOT NULL ,
    [state] [varchar]   (32),
    [city] [varchar]  (32) NOT NULL ,
    [federation] [varchar]  (32) NOT NULL ,
    [id] [int] NOT NULL ,
    [price] [int] NOT NULL );

INSERT data values(2012, 12, 'France', NULL, 'Paris', 'FFJ', 1, 23)
INSERT data values(2013, 2, 'France', NULL, 'Paris', 'FFV', 2, 212)
INSERT data values(2012, 1, 'USA', 'CA', 'Paris', 'FFV', 3, 23)
INSERT data values(2013, 12, 'France', NULL, 'Paris', 'FFV', 4, 273)
INSERT data values(2012, 9, 'USA', 'OR', 'Lake Oswego', 'FFV', 5, 743)
INSERT data values(2012, 11, 'France', NULL, 'Paris', 'FFJ', 6, 3)
INSERT data values(2012, 12, 'France', NULL, 'Paris', 'FFV', 7, 231)
INSERT data values(2012, 12, 'USA', 'CA', 'St Monica', 'FFV', 8, 41)
INSERT data values(2012, 12, 'France', NULL, 'Paris', 'FFV', 9, 96)
INSERT data values(2012, 12, 'France', NULL, 'Vire', 'FFJ', 10, 23)
INSERT data values(2012, 12, 'France', NULL, 'Paris', 'FFV', 11, 58)
INSERT data values(2012, 12, 'France', NULL, 'Nice', 'FFV', 12, 773)

我按列year, month, country, state, federation, city进行分组。

我使用ROLLUP运算符,因为我需要在多个级别上获得总计。但我还想将CUBE应用于两个列country(地理属性)和federation(以及组织属性)。

如果我在查询中只是CUBE,我得到的输出比我需要的多得多。 (我真的不需要将CUBE应用到我的所有GROUP BY列。)

是否存在变通方法?

1 个答案:

答案 0 :(得分:2)

SQL Server 2000仅支持不符合ISO标准的GROUP BY ... WITH ROLLUPGROUP BY ... WITH CUBE,这两种语法不具备很大的灵活性。您只能拥有完整的汇总/多维数据集,没有变化或组合。

但是,在您的特定情况下的解决方法可能不会太麻烦。 ROLLUP会给你以下分组:

year, month, country, state, federation, city
year, month, country, state, federation
year, month, country, state
year, month, country
year, month
year
()  -- grand total

我对你想要的东西的理解是这样的:

year, month, country, state, federation, city
year, month, country, state, federation
year, month, country, state
year, month, country, federation
year, month, country
year, month
year
()

显然你需要在ROLLUP输出中再添加一个分组子集,即这一个:

year, month, country, federation

您可以在单独的SELECT中计算它并将结果与​​UNION ALL:

组合
SELECT ...
FROM dbo.data
GROUP BY
  year, month, country, state, federation, city
  WITH ROLLUP

UNION ALL

SELECT ...
FROM dbo.data
GROUP BY
  year, month, country, federation
;
相关问题