【发布时间】:2016-03-15 07:15:20
【问题描述】:
假设我有这样一张桌子:
表1
EmployeeID Month sym Quantity V_M BudjetCode
222222 1 40 133.35 1214 800000
222222 2 40 178.50 115 800000
222222 3 40 150.33 215 800000
222222 4 40 186.37 315 800000
222222 5 40 127.38 415 800000
222222 6 40 153.00 515 800000
222222 7 40 178.50 615 800000
222222 7 40 8.50 615 700052015
222222 8 40 187.00 715 800000
我想把这张表改成:
表 2
EmployeeID Month sym Quantity V_M BudjetCode
222222 1 40 133.35 1214 800000
222222 2 40 178.50 115 800000
222222 3 40 150.33 215 800000
222222 4 40 186.37 315 800000
222222 5 40 127.38 415 800000
222222 6 40 161.5 515 800000
222222 7 40 178.50 615 800000
222222 8 40 187.00 715 800000
怎么样? 请参阅表 1 中 BudjetCode 异常的行?
好吧,对于这一行,我想将 Quantity 值 (8.5) 添加到 V_M 比 V_M 小一的行是原始行(其中 budjetCode 为 700052015)。
在示例中,原来是 615,所以减一是 515(615 表示日期 6.15,515 表示 5.15),我需要添加数量(8.5 到 153 = 161.5)
我在想“过度分区”:
select [EmployeeID],[Month],[Sym],
sum([Quantity])
over (partition by [EmployeeID], [V_M]-1 where???) as b
from table1
where [Sym] = '40' and [EmployeeID] = 222222
order by [Month]
但我不知道如何使用 budjetCode 以“700”开头的标准来总结。
评论:不要在第一行这样做。
更新:
EmployeeID month Quantity V_M MS_BudjetCode
22222 1 40 133.35 1214 88888888
22222 2 40 178.50 115 88888888
22222 3 40 150.33 215 88888888
22222 4 40 186.37 315 88888888
22222 5 40 127.38 415 88888888
22222 6 40 153.00 515 88888888
22222 7 40 8.50 615 700000000
22222 7 40 178.50 615 88888888
22222 8 40 187.00 715 88888888
输出:
22222 2 40 178.50 115 88888888
22222 4 40 186.37 315 88888888
22222 8 40 187.00 715 88888888
22222 3 40 151.33 215 88888888
22222 3 40 151.33 215 88888888
22222 3 40 151.33 215 88888888
22222 3 40 149.33 215 88888888
22222 3 40 149.33 215 88888888
22222 5 40 127.38 415 88888888
22222 6 40 152.00 515 88888888
22222 6 40 154.00 515 88888888
22222 6 40 152.00 515 88888888
22222 6 40 154.00 515 88888888
22222 6 40 154.00 515 88888888
22222 6 40 152.00 515 88888888
22222 6 40 161.50 515 88888888
22222 7 40 178.50 615 88888888
22222 1 40 133.35 1214 88888888
查询:
SELECT t1.EmployeeID, t1.Month, t1.sym,
t1.Quantity + COALESCE(t2.Quantity, 0),
t1.V_M, t1.BudjetCode
FROM Table1 AS t1
LEFT JOIN Table1 AS t2
ON t1.EmployeeID = t2.EmployeeID AND t1.V_M = t2.V_M - 100 AND
SUBSTRING(t2.BudjetCode,1,3) = '700'
WHERE SUBSTRING(t1.BudjetCode,1,3) <> '700' and sym='40' and EmployeeID = 22222
【问题讨论】:
标签: sql sql-server-2008 select sql-update