0

I have a Table with Data as

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

From this Data I want to Select All Records where The Sum of Ticket Count will be equal to 10(user input value)

In the Given data I want to Select all Records till Row Index 9. Output should be:

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
4

2 回答 2

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;
于 2013-08-07T13:36:21.310 回答
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 演示

于 2013-08-07T13:38:23.523 回答