2017-06-12 60 views
1

在下面的查詢中,我想檢索@MaximumRecords行,以便沒有任何ProjectId將行留在@MaximumRecords之外。限制SQL Server中的選定行

例如,如果@ MaximumRecords = 100,並且ProjectId = 7在99-102行有記錄,我希望僅檢索ProjectId = 1到ProjectId = 6的行(查詢將在稍後從ProjectId = 7)。我怎麼做?

SELECT TOP (@MaximumRecords) 
    t1.ProjectId, 
    t1.Row2, 
    t2.Row3 
FROM Table1 t1 
    JOIN Table2 t2 ON t1.ProjectId = t2.ProjectId 
ORDER BY 
    t1.ProjectId ASC 
WHERE 
    t1.ProjectId > @InitialProjectId 

回答

0

我工作起來使用Sales.SalesOrderHeaderSales.SalesOrderDetail表的解決方案在AdventureWorks2008R2數據庫中使用該技術來獲得運行總計描述here

基本思路是獲取每個SalesOrderID(您的案例中的ProjectID)的計數的運行總計,然後選擇所有計數的運行總計小於@MaximumRecords的SalesOrderID的所有數據。然後,您需要捕獲返回數據中的最大ID,並在查詢的下一次運行中使用該值。

使用上面給出的鏈接中描述的SQL Server 2012,該任務變得更容易一些。

這...

USE AdventureWorks2008R2 

IF OBJECT_ID('tempdb..#Test', 'U') IS NOT NULL DROP TABLE #Test; 

DECLARE @MaximumRecords INT 
DECLARE @InitialSalesOrderID INT 

SET @MaximumRecords = 500 
SET @InitialSalesOrderID = 43663 

SELECT a.SalesOrderID, COUNT(*) AS 'Count' 
INTO #Test 
FROM Sales.SalesOrderHeader a 
INNER JOIN Sales.SalesOrderDetail b ON a.SalesOrderID = b.SalesOrderID 
WHERE a.SalesOrderID > @InitialSalesOrderID 
GROUP BY a.SalesOrderID 

SELECT * FROM Sales.SalesOrderHeader a 
INNER JOIN Sales.SalesOrderDetail b ON a.SalesOrderID = b.SalesOrderID 
WHERE a.SalesOrderID IN (
SELECT 
    a.SalesOrderID 
FROM 
    #Test a 
WHERE (
    SELECT 
     SUM(Count) 
    FROM 
     #Test b 
    WHERE 
     b.SalesOrderID <= a.SalesOrderID 
    ) < @MaximumRecords 
) 

諾埃爾