我很难找到一种方法来对字段'因素'上的整个表执行更新。
'因子'由具有相同位置的重复记录的数量决定。和' date'。
有一个因子计算表:
Location - Count - Factor
X - 1 - 1.0
X - 2 - 0.8
X - 3+ - 0.5
请帮帮我!
答案 0 :(得分:2)
试试这个:
UPDATE A
SET Factor = CASE WHEN B.N = 1 THEN 1.0
WHEN B.N = 2 THEN 0.8
WHEN B.N >= 3 THEN 0.5 END
FROM YourTable A
INNER JOIN (SELECT Location, COUNT(*) N
FROM YourTable
GROUP BY Location) B
ON A.Location = B.Location
另一种方式:
;WITH CTE AS
(
SELECT *, COUNT(*) OVER(PARTITION BY Location) N
FROM YourTable
)
UPDATE CTE
SET Factor = CASE WHEN N = 1 THEN 1.0
WHEN N = 2 THEN 0.8
WHEN N >= 3 THEN 0.5 END
答案 1 :(得分:0)
将派生表与OVER子句
一起使用UPDATE x
SET x.Factor = x.NewFactor
FROM (
SELECT Factor,
CASE COUNT(*) OVER (PARTITION BY Location, [date])
WHEN 1 THEN 1.0
WHEN 2 THEN 0.8
ELSE 0.5 END AS NewFactor
FROM dbo.test30
) x
SQLFiddle上的演示