2012-03-04 75 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

相關問題