2013-08-07 59 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