我陷入了SQL查询,
我有一个表薪水,其结构如下:
Name Amount
a 100
b 300
c 250
我必须编写一个查询,其结果如下:
Name Amount RelevantAmount
a 100 100
b 300 400
c 250 650
我没有发现如何在不使用任何游标和触发器的情况下编写此查询。
答案 0 :(得分:4)
假设您希望总结列表中包含当前行的所有内容的数量,最简单的(但不一定是最有效的)答案将使用相关查询:
select
name
, amount
, (select sum(amount) from MyTable t2 where t1.name <= t2.name) RelevantAmount
from MyTable t1
order by t1.Name
答案 1 :(得分:3)
试试这个:
SELECT a.Name, a.Amount, SUM(b.Amount) as RelevantAmount
FROM myTable a
JOIN myTable b
ON b.Name <= a.Name
GROUP BY a.Name, a.Amount
ORDER BY a.Name ASC
答案 2 :(得分:2)
据我理解你的问题,你可以这样做:
SELECT name,
SUM(amount) AS month_amount,
SUM(SUM(amount)) OVER
(ORDER BY amount ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
AS cumulative_amount
FROM table_name
GROUP BY name
ORDER BY name;