1

我一直试图找出一种方法来对字段“因子”上的整个表执行更新。

“因子”由具有相同“位置”和“日期”的重复记录的数量确定。

有一个因子计算表:

Location - Count - Factor
   X     -   1    -   1.0
   X     -   2    -   0.8
   X     -   3+    -  0.5

请帮帮我!

4

2 回答 2

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
于 2013-01-25T20:53:54.073 回答
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上的演示

于 2013-01-25T21:58:28.663 回答