1. 程式人生 > >SQL2008避免出錯(聚合函式+Over用法)

SQL2008避免出錯(聚合函式+Over用法)

--返回出錯
with CTEOrders as
	(select cast(1 as int) as OrderID, cast('3/1/2012' as date) as OrderDate, cast(10.00 as money) as OrderAmt, 'Joe' as CustomerName
	union select 2, '3/1/2012', 11.00, 'Sam'
	union select 3, '3/2/2012', 10.00, 'Beth'
	union select 4, '3/2/2012', 15.00, 'Joe'
	union select 5, '3/2/2012', 17.00, 'Sam'
	union select 6, '3/3/2012', 12.00, 'Joe'
	union select 7, '3/4/2012', 10.00, 'Beth'
	union select 8, '3/4/2012', 18.00, 'Sam'
	union select 9, '3/4/2012', 12.00, 'Joe'
	union select 10, '3/4/2012', 11.00, 'Beth'
	union select 11, '3/5/2012', 14.00, 'Sam'
	union select 12, '3/6/2012', 17.00, 'Beth'
	union select 13, '3/6/2012', 19.00, 'Joe'
	union select 14, '3/7/2012', 13.00, 'Beth'
	union select 15, '3/7/2012', 16.00, 'Sam'
	)
select sum(OrderAmt), sum(OrderAmt) over()
   from CTEOrders
   group by CustomerName
 /*
 訊息 155,級別 15,狀態 1,第 24 行
'CTEOrders' 不是可以識別的 GROUP BY 選項。
*/  
--這樣用避免出錯
;with CTEOrders as
	(select cast(1 as int) as OrderID, cast('3/1/2012' as date) as OrderDate, cast(10.00 as money) as OrderAmt, 'Joe' as CustomerName
	union select 2, '3/1/2012', 11.00, 'Sam'
	union select 3, '3/2/2012', 10.00, 'Beth'
	union select 4, '3/2/2012', 15.00, 'Joe'
	union select 5, '3/2/2012', 17.00, 'Sam'
	union select 6, '3/3/2012', 12.00, 'Joe'
	union select 7, '3/4/2012', 10.00, 'Beth'
	union select 8, '3/4/2012', 18.00, 'Sam'
	union select 9, '3/4/2012', 12.00, 'Joe'
	union select 10, '3/4/2012', 11.00, 'Beth'
	union select 11, '3/5/2012', 14.00, 'Sam'
	union select 12, '3/6/2012', 17.00, 'Beth'
	union select 13, '3/6/2012', 19.00, 'Joe'
	union select 14, '3/7/2012', 13.00, 'Beth'
	union select 15, '3/7/2012', 16.00, 'Sam'
	)
select sum(OrderAmt), sum(sum(OrderAmt)) over()
   from CTEOrders
   group by CustomerName
;
/*
61.0000	205.0000
68.0000	205.0000
76.0000	205.0000
*/