bestlong 怕失憶論壇

 

 

搜索
bestlong 怕失憶論壇 論壇 Database - 資料庫 MS SQL Server 群組資料取 Top 1
查看: 8686|回復: 0
go

群組資料取 Top 1 [複製鏈接]

Rank: 9Rank: 9Rank: 9

1#
發表於 2006-12-21 12:23 |只看該作者 |倒序瀏覽 |打印
整理使用三種方法來取得資料: [Inner Join]、[SubQuery]、[ROW_NUMBER()],檢視其執行計畫後,
成本最低是:[SubQuery]。

請參考以下的範例:
  1. USE Northwind
  2. GO

  3. /*
  4. 假設 ProductID 是自動編號,CategoryID 則是群組編號值,取得資料表每一個資料行。
  5. */

  6. -- Inner Join , COST = 0.0170818
  7. SELECT P1.ProductID, P1.ProductName, P1.SupplierID, P1.CategoryID, P1.QuantityPerUnit,
  8. P1.UnitPrice, P1.UnitsInStock, P1.UnitsOnOrder, P1.ReorderLevel, P1.Discontinued
  9. FROM Products P1 INNER JOIN Products P2
  10. ON P1.CategoryID = P2.CategoryID
  11. GROUP BY P1.ProductID, P1.ProductName, P1.SupplierID, P1.CategoryID, P1.QuantityPerUnit,
  12. P1.UnitPrice, P1.UnitsInStock, P1.UnitsOnOrder, P1.ReorderLevel, P1.Discontinued
  13. HAVING P1.ProductID = min(P2.ProductID)

  14. -- SubQuery , COST =  0.007844
  15. SELECT P1.*
  16. FROM Products P1
  17. WHERE p1.ProductID =
  18. (
  19. SELECT min(p2.ProductID)
  20. FROM Products P2
  21. WHERE P1.CategoryID = P2.CategoryID
  22. )

  23. -- ROW_NUMBER() -- Support SQL Server 2005 , COST =  0.0155255
  24. SELECT ProductID, ProductName, SupplierID, CategoryID, QuantityPerUnit, UnitPrice,
  25. UnitsInStock, UnitsOnOrder, ReorderLevel, Discontinued
  26. FROM (
  27. SELECT ROW_NUMBER() OVER(PARTITION BY CategoryID ORDER BY ProductID) 'rown',
  28. *
  29. FROM    Products ) AS TN
  30. WHERE rown = 1
複製代碼
Best Regards
Derrick Chen 德瑞克
我是雪龍
http://blog.bestlong.idv.tw
http://www.bestlong.idv.tw
‹ 上一主題|下一主題

Archiver|怕失憶論壇

GMT+8, 2024-4-25 06:16 , Processed in 0.014719 second(s), 11 queries .

Powered by Discuz! X1.5

© 2001-2010 Comsenz Inc.