我正在关注本系列文章以了解ROLLUP和CUBE
对于此查询:
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
立方体生成的两个额外行是最后两行。我得到这样的结果:
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 :(得分:2)
IIRC SQL不保证任何订单,除非您明确地拥有ORDER BY
...有时不同的SQL Server版本/补丁级别在没有ORDER BY
的情况下“订购”。
我不知道作者是否使用SQL Server 2005或2008或2008 R2等产生了这个结果。但我高度怀疑这就是你看到的原因......
如果您需要在结果集中使用特定顺序,请始终使用明确的ORDER BY
子句!