我正在撰写一份生产记录报告,但我遇到了一些困难。以下是我要完成的任务:
让我们说我正在创建一个包含3列的临时表:
表:#TProductionRecords
第1列:Part_No
Quantity
Total_Quantity
任何给定的部件可能在任何一天以不同的数量生产多次:
row 1: part1 55
row 2: part1 105
row 3: part1 70
row 4: part2 100
row 5: part2 25
row 6: part3 150
row 7: part3 50
row 8: part3 35
row 9: part3 80
等。
我希望Total_Quantity
列开始运行总计,然后在有新部件时重置。我已经有了选择查询,但我不知道如何添加Total_Quantity
列。
任何帮助都会很棒!
由于
答案 0 :(得分:1)
在不知道结果顺序的情况下,这会使用correlated subquery
和common-table-expression
来随机对row_number
命名记录:
with cte as (
select *,
row_number() over (partition by part_no order by (select null)) rn
from yourtable
)
select part_no,
quantity,
(select sum(quantity)
from cte c2
where c2.rn <= c1.rn and c1.part_no = c2.part_no) total_qty
from cte c1
order by c1.part_no, c1.rn
根据几条评论,关于订单的问题很重要。 SQL Server不保证返回结果的顺序。因此,运行总计有时可以从Part1 / 55开始,也可能在Part1 / 105其他时间开始 - 很多决定因素。您最好定义一个订单以返回结果。
答案 1 :(得分:0)
DECLARE @Table TABLE ( Part VARCHAR(100), Qty INT)
INSERT INTO @Table VALUES
('part1', 55),
('part1', 105),
('part1', 70 ),
('part2', 100),
('part2', 25),
('part3', 150),
('part3', 50),
('part3', 35),
('part3', 80)
SELECT t.* , ISNULL(C.RunningTotal, 0) + t.Qty AS RunningTotal
FROM @Table t
CROSS APPLY (SELECT SUM(Qty)
FROM @Table
WHERE t.Part = Part
AND t.Qty > Qty)c(RunningTotal)
ORDER BY t.Part, t.Qty
╔═══════╦═════╦══════════════╗
║ Part ║ Qty ║ RunningTotal ║
╠═══════╬═════╬══════════════╣
║ part1 ║ 55 ║ 55 ║
║ part1 ║ 70 ║ 125 ║
║ part1 ║ 105 ║ 230 ║
║ part2 ║ 25 ║ 25 ║
║ part2 ║ 100 ║ 125 ║
║ part3 ║ 35 ║ 35 ║
║ part3 ║ 50 ║ 85 ║
║ part3 ║ 80 ║ 165 ║
║ part3 ║ 150 ║ 315 ║
╚═══════╩═════╩══════════════╝
答案 2 :(得分:0)
除上述答案外,Running totals
还可以通过以下方法计算
方法1: Correlated Subquery
SELECT *,
(SELECT Sum(Qty)
FROM @Table t
WHERE t.Part = a.Part
AND t.Qty <= a.Qty)
FROM @Table a
ORDER BY a.Part,a.Qty
方法2: Self Join
SELECT a.Part,
a.Qty,
Sum(b.qty)
FROM @Table A
JOIN @Table b
ON a.Part = b.Part
AND a.Qty >= b.Qty
GROUP BY a.Part,a.Qty
ORDER BY a.Part,a.Qty