2012-03-04 77 views
0

我下面这个系列文章,了解ROLLUP和CUBE相同的查询获取不同的结果

http://beyondrelational.com/modules/2/blogs/28/posts/10471/tsql-lab-6-using-with-cube-to-generate-subtotal-and-grand-total-rows.aspx

对于此查询:

select 
    case 
     when grouping(CustomerName) = 1 then 'All Customers' 
     else CustomerName 
    end as CustomerName, 
    case 
     when grouping(ItemName) = 1 then 'All Items' 
     else ItemName 
    end as ItemName, 
    sum(quantity*pricepercase) as Amount1 
from orders 
group by CustomerName, ItemName 
with cube 

笔者结果是这样的:

CustomerName   ItemName    Amount 
-------------------- -------------------- --------------------- 
Jacob    Item 1    312.50 
Jacob    Item 2    480.00 
Jacob    All Items   792.50 
Mike     Item 1    75.00 
Mike     Item 2    44.00 
Mike     All Items   119.00 
All Customers  All Items   911.50 
All Customers  Item 1    387.50 
All Customers  Item 2    524.00 

由多维数据集生成的两个额外的行是最后2行。我得到如下结果:

CustomerName   ItemName    Amount 
-------------------- -------------------- --------------------- 
Jacob    Item 1    312.50 
Mike     Item 1    75.00 
All Customers  Item 1    387.50 
Jacob    Item 2    480.00 
Mike     Item 2    44.00 
All Customers  Item 2    524.00 
All Customers  All Items   911.50 
Jacob    All Items   792.50 
Mike     All Items   119.00 

第一个结果集看起来合适。为什么运行它时会有什么不同?

+0

编辑为包含查询。 – Animesh 2012-03-04 10:46:40

+2

不要使用'WITH CUBE' http://msdn.microsoft.com/en-us/library/ms177673.aspx *对所有新工作使用符合ISO的语法。为了向后兼容,提供了非ISO兼容语法。* – 2012-03-04 10:58:00

+0

哦!很高兴知道。 'CUBE(elem1,elem2)'而不是'WITH CUBE' – Animesh 2012-03-04 11:02:12

回答

2

IIRC SQL不保证任何顺序,除非明确地有ORDER BY适当的位置......有时不同的SQL Server版本/修补程序级别“顺序”不同,没有ORDER BY

我不知道作者是否使用SQL Server 2005或2008或2008 R2等产生的结果,但我higghly怀疑这是你看到的是什么原因...

如果您需要结果集中的特定顺序始终使用明确的ORDER BY子句!

+0

好吧,我怀疑它可能是那个顺序不能保证。但是,如果我使用'rollup'而不是'cube',则获得与作者相同的结果顺序。那是当我想知道它可能是别的什么。如您所说,作者可能使用过不同版本的SQL Server。 – Animesh 2012-03-04 10:59:22

+0

如果事实证明是不同版本的情况,版本中是否有以不同顺序生成结果的功能? – Animesh 2012-03-04 11:00:54

+0

@KishorNanda任何数据库供应商可以随意更改内部算法,只要结果是符合标准的,他们想要的任何方式 - 这使得它很难说有可能与这种变化? – Yahia 2012-03-04 11:05:01

相关问题