web-dev-qa-db-ja.com

SQL Serverで列の実行中の合計を取得する方法

こんにちは、テーブルBillsのQtyという名前の列があります。次のようなQty列の現在の合計を表示する列が必要です。

Qty   Run_Sum
1      1
2      3
3      6
4      10
5      15

Thankxを実行するための適切な方法を提案する

14
user1448783

SQLFiddleデモ

SELECT Qty,
SUM(Qty) OVER (ORDER BY Qty) Run_Sum
FROM t ORDER BY Qty

2012年より前のSQLServerの場合:

select Qty,
(select sum(Qty) from t where Qty<=t1.Qty)
from t t1 order by Qty

SQLFiddleデモ

または、サブクエリなしでも実行できます。

select t1.Qty, sum(t2.Qty)
from t t1 
join t t2 on (t1.Qty>=t2.Qty)
group by t1.Qty
order by t1.Qty

SQLFiddleデモ

12
valex

rDBMSがウィンドウ機能をサポートしている場合、

にとって SQL Server 2012

SELECT  Qty,
        SUM(Qty) OVER (ORDER BY Qty) AS CumulativeTOTAL
FROM    tableName

にとって SQL Server 2008

SELECT a.Qty, (SELECT SUM(b.Qty)
               FROM   TableName b
               WHERE  b.Qty <= a.Qty)
FROM   TableName a
ORDER  BY a.Qty;
12
John Woo

Oracle /分析関数を使用したサンプルは次のとおりです。

select id, qty, sum(qty) over(order by id asc) run_sum
from test;

http://www.sqlfiddle.com/#!4/3d149/1

1
Lloyd Santos

@mahmud:これが与えるものを見る

DECLARE @Bills table
(
    QUANTITY int
)

INSERT INTO @Bills
SELECT 2 UNION ALL
SELECT 6 UNION ALL
SELECT 7 UNION ALL
SELECT 1 UNION ALL
SELECT 3 UNION ALL
SELECT -5 UNION ALL
SELECT 5 UNION ALL
select 1

;with cte as (
  select top 1 QUANTITY, QUANTITY as RunningSum
  from @Bills
  order by QUANTITY

  union all

  select t.QUANTITY, cte.RunningSum + t.QUANTITY
  from cte
  inner join @Bills t on cte.QUANTITY + 1 = t.QUANTITY
)
select * from cte
0
Varun
;with cte as (
  select top 1 Qty, Qty as RunningSum
  from Bills
  order by Qty

  union all

  select t.Qty, cte.RunningSum + t.Qty
  from cte
  inner join Bills t on cte.Qty + 1 = t.Qty
)
select * from cte
0
muhmud

これをチェックして

DECLARE @TEMP table
(
    ID int IDENTITY(1,1),
    QUANTITY int
)

INSERT INTO @TEMP
SELECT 1 UNION ALL
SELECT 2 UNION ALL
SELECT 3 UNION ALL
SELECT 4 UNION ALL
SELECT 8 UNION ALL
SELECT 7 UNION ALL
SELECT 5 UNION ALL
SELECT 1

SELECT t.QUANTITY AS Qty, SUM(t1.QUANTITY) AS Run_Sum
FROM @TEMP t
INNER JOIN @TEMP t1
ON t1.ID <= t.ID
GROUP BY t.ID, t.QUANTITY
ORDER BY t.ID
0
vikas