根据另一列的总和值选择数据

时间:2013-08-07 13:33:57

标签: sql sql-server sql-server-2008

我有一个数据表为

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 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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

相关问题