2013-08-07 54 views
0

我有一個數據表作爲選擇數據的另一列看重

RowIndex Id TicketCount 
1   23 1 
2   25 2 
3   3 1 
4   14 1 
5   16 1 
6   18 1 
7   1 1 
8   6 1 
9   15 1 ===> at this row the sum of Ticket Count is 10 
10   22 1 
11   27 1 
12   24 1 
13   26 2 
14   9 1 
15   19 1 

從這個數據我想選擇所有記錄,其中門票計數之和將等於10(用戶輸入值)

在給定的數據我想選擇所有記錄,直到行索引9 輸出應該是:

RowIndex Id TicketCount 
1   23 1 
2   25 2 
3   3 1 
4   14 1 
5   16 1 
6   18 1 
7   1 1 
8   6 1 
9   15 1 

回答

2

SQL Server 2008中不具備的累積和功能。我實現使用相關子查詢它:

select RowIndex, Id, TicketCount 
from (select t.*, 
      (select sum(TicketCount) 
       from t t2 
       where t2.RowIndex <= t.RowIndex 
      ) as cumTicketCount 
     from t 
    ) t 
where cumTicketCount <= 10; 

在SQL Server 2012中,您可以短語這個使用窗函數:

select RowIndex, Id, TicketCount 
from (select t.*, sum(TicketCount) over (order by RowIndex) as CumTicketCount 
     from t 
    ) t 
where cumTicketCount <= 10; 
+0

在Oracle中,你也可以使用LAG功能。 – Randy

+0

@Randy。 。 。在Oracle中(這個問題沒有被標記),我只是簡單地使用累計求和函數。就像我在Postgres和DB2--支持它的其他數據庫一樣。 –

+0

是不是比SQL 2012年早的窗口函數'over(按RowIndex排序)? – xanatos

1

可以使用遞歸CTE做到這一點:

WITH RCTE AS 
(
    SELECT *, TicketCount AS Total 
    FROM Table1 
    WHERE RowIndex = 1 

    UNION ALL 

    SELECT t.*, r.Total + t.TicketCount 
    FROM RCTE r 
    INNER JOIN Table1 t ON r.RowIndex + 1 = t.RowIndex 
    WHERE r.Total + t.TicketCount <= 10 --your input value 
) 
SELECT * FROM RCTE 

SQLFiddle DEMO