将两列的值相加并显示在下一行
Posted
技术标签:
【中文标题】将两列的值相加并显示在下一行【英文标题】:Sum values of two columns and display in next row 【发布时间】:2020-12-04 07:38:35 【问题描述】:我有一个如下所示的表格:
select * from #tempTable
RN Qty
0 30
1 -3
2 -2
3 8
使用下面的查询,我可以做到以下几点:
WITH CTE AS
(SELECT ROW_NUMBER()OVER(ORDER BY RN) AS RN, Qty
FROM #tempTable)
SELECT T1.RN,T1.Qty StartingQty,T2.Qty as ChangedQty, (T1.Qty+T2.Qty) as TotalQty
FROM CTE T1 LEFT JOIN
CTE T2 ON T1.RN=(T2.RN-1) where T2.Qty IS not null
结果如下:
RN StartingQty ChangedQty TotalQty
1 30 -3 27
2 -3 -2 -5
3 -2 8 6
结果应该如下所示,不知道如何实现:
RN StartingQty ChangedQty TotalQty
1 30 -3 27
2 27 -2 25
3 25 8 33
任何线索都会对如何实现这一点有所帮助。
【问题讨论】:
SQL Server 版本是多少? 管理工作室 2018,版本 2016 正如我在 2016 年上面所说的。 【参考方案1】:您可以尝试使用LEAD()
和窗口化SUM()
的方法:
SELECT *
FROM (
SELECT
RN,
SUM(Qty) OVER (ORDER BY RN) AS StartingQty,
LEAD(Qty) OVER (ORDER BY RN) AS ChangedQty,
SUM(Qty) OVER (ORDER BY RN) + LEAD(Qty) OVER (ORDER BY RN) AS TotalQty
FROM (VALUES
(0, 30),
(1, -3),
(2, -2),
(3, 8)
) v (RN, Qty)
) t
WHERE ChangedQty IS NOT NULL
结果:
RN StartingQty ChangedQty TotalQty
0 30 -3 27
1 27 -2 25
2 25 8 33
【讨论】:
【参考方案2】:您可以使用窗口函数和窗口框架获取基本值:
select rn, qty as StartingQty,
lead(qty) over (order by rn) as ChangedQty,
sum(qty) over (order by rn rows between unbounded preceding and 1 following) as TotalQty
from (values (0, 30),
(1, -3),
(2, -2),
(3, 8)
) v (rn, Qty);
要消除最后一行,唉,你需要一个子查询:
select t.*
from (select rn, qty as StartingQty,
lead(qty) over (order by rn) as ChangedQty,
sum(qty) over (order by rn rows between unbounded preceding and 1 following) as TotalQty
from (values (0, 30),
(1, -3),
(2, -2),
(3, 8)
) v (rn, Qty)
) t
where changedqty is not null;
Here 是一个 dbfiddle。
【讨论】:
以上是关于将两列的值相加并显示在下一行的主要内容,如果未能解决你的问题,请参考以下文章
不能在 QTableWidget 中添加两列。错误 - DeprecationWarning:需要一个整数(获取类型浮点数)