sql sum[count,avg,min,max等等] over(PARTITION BY 列名稱1,列名稱2。。。) 和sum。。。goup by 。。。的差別
USE db_sql2005 GO SELECT 訂單編號,商品編號,訂貨數量 ,SUM(訂貨數量) OVER(PARTITION BY 訂單編號) AS '總計' ,COUNT(訂貨數量) OVER(PARTITION BY 訂單編號) AS '計數' ,AVG(訂貨數量) OVER(PARTITION BY 訂單編號) AS '平均' ,MIN(訂貨數量) OVER(PARTITION BY 訂單編號) AS '最小' ,MAX(訂貨數量) OVER(PARTITION BY 訂單編號) AS '最大' FROM tb_Sale WHERE 訂單編號 IN('DD1305','DD1306') GO
類似於:
SELECT 訂單編號,商品編號,訂貨數量 , (SELECT SUM(訂貨數量) FROM tb_Sale t2 WHERE 訂單編號=t.訂單編號) AS '總計' ,(SELECT COUNT(訂貨數量) FROM tb_Sale t2 WHERE 訂單編號=t.訂單編號) ,COUNT(訂貨數量) OVER(PARTITION BY 訂單編號) AS '計數' ,AVG(訂貨數量) OVER(PARTITION BY 訂單編號) AS '平均' ,MIN(訂貨數量) OVER(PARTITION BY 訂單編號) AS '最小' ,MAX(訂貨數量) OVER(PARTITION BY 訂單編號) AS '最大' FROM tb_Sale t WHERE 訂單編號 IN('DD1305','DD1306')
對比於 sum() group by
USE db_sql2005 GO SELECT 訂單編號 ,SUM(訂貨數量) AS '總計' FROM tb_Sale WHERE 訂單編號 IN('DD1305','DD1306')
GROUP BY 訂單編號
USE db_sql2005 GO SELECT DISTINCT 訂單編號 ,(SELECT SUM(訂貨數量) FROM tb_Sale t2 WHERE 訂單編號=t.訂單編號) AS '總計' FROM tb_Sale t WHERE 訂單編號 IN('DD1305','DD1306')
所以 group by 和 PARTITION BY 它們對應的統計結果值是一樣的,但是前者是去重複,後者是沒有去重複的。