我有一张桌子:
django-storages
我希望每组按id,vals的总和= 0,如果vals<> 0,因此每组中的和的结果随着第一个val减少。例如,在id = 1 ==> sum =(8)+( - 10)+(5)+( - 2)= 1,如果val的row1减1,则sum等于0和ok。
+------+------+-------+------+----------+
| id | year | val | row | whatever |
+------+------+-------+------+----------+
| 001 | 2006 | 8 | 1 | p01 |
| 001 | 2003 | -10 | 2 | p01 |
| 001 | 2008 | 5 | 3 | p01 |
| 001 | 2001 | -2 | 4 | p01 |
| 002 | 2007 | 5 | 1 | p01 |
| 002 | 2009 | 4 | 2 | p01 |
| 002 | 2002 | -5 | 3 | p01 |
| 002 | 2004 | -4 | 4 | p01 |
| 003 | 2005 | 15 | 1 | p01 |
| 003 | 2000 | -18 | 2 | p01 |
| 003 | 2001 | -12 | 3 | p02 |
| 003 | 2004 | 12 | 4 | p02 |
| 003 | 2002 | 12 | 5 | p02 |
| 004 | 2003 | 5 | 1 | p02 |
| 004 | 2000 | -8 | 2 | p02 |
| 004 | 2006 | 4 | 3 | p02 |
| 004 | 2007 | 3 | 4 | p02 |
+------+------+-------+------+----------+
此示例中的正确解决方案是什么?
答案 0 :(得分:2)
您可以使用SUM
的窗口版本来计算每个val
分区的id
总和。然后将您的查询包装在CTE中并更新CTE:
;WITH ToUpdate AS (
SELECT id, row, val, SUM(val) OVER (PARTITION BY id) AS sumVal
FROM mytable
)
UPDATE ToUpdate
SET val = val - sumVal
WHERE row = 1