根据同一个表中的另一列更新空列

时间:2017-01-14 09:40:23

标签: sql sql-server sql-update sql-server-2014

我有一个表point,其中包含以下(示例)数据:

datekey pointkey  filter_key  t_key                            
-----------------------------------
  (5506061, 37, NULL, 1),
(5506061, 37, NULL, 1),
(5506061, 37, NULL, 1),
(5506061, 37, NULL, 1),
(5506061, 37, NULL, 1),
(5506061, 37, NULL, 1),
(5506763, 37, NULL, 2),
(5506763, 37, NULL, 2),
(5506763, 37, NULL, 2),
(45643, 97, NULL, 2),
(45643, 97, NULL, 2),
(45643, 97, NULL, 2),
(45643, 97, NULL, 2),
(45643, 97, NULL, 2),
(45643, 97, NULL, 2),
(1234, 83, NULL, 1),
(1234, 83, NULL, 1),
(1234, 83, NULL, 1),
(1234, 83, NULL, 1),
(1234, 83, NULL, 1),
(1234, 83, NULL, 1),
(1234, 84, NULL, 1),
(1234, 84, NULL, 1),
(1234, 84, NULL, 1),
(1234, 84, NULL, 1),
(1234, 84, NULL, 1),
(1234, 84, NULL, 1),
(45645, 97, NULL, 1),
(45645, 97, NULL, 2),
(45645, 97, NULL, 2),
(45645, 97, NULL, 2),
(45645, 97, NULL, 2),
(45645, 97, NULL, 2)

上述行的组合可以相同1-6次。我的意思就像上面例子中的前6行。这个表中没有唯一的密钥。这个表有几百万行,如上所述。

我想更新此表以填充NULL列(filter_key)。在这列中,我想要值1和2.当在t_key列中它为'2'时,2必须也在filter_key列中。当它在t_key列中的1时我只想在第一个记录中的'1'一次,所有其他列必须是'2'。

所以上面提到的代码必须转移到:

5506061 37        1        1
5506061 37        2        1
5506061 37        2        1
5506061 37        2        1
5506061 37        2        1
5506061 37        2        1
5506763 37        2        2
5506763 37        2        2
5506763 37        2        2
45643   97        2        2
45643   97        2        2
45643   97        2        2
45643   97        2        2
45643   97        2        2
45643   97        2        2
1234    83        1        1
1234    83        2        1
1234    83        2        1
1234    83        2        1
1234    83        2        1
1234    83        2        1
1234    84        1        1
1234    84        2        1
1234    84        2        1
1234    84        2        1
1234    84        2        1
1234    84        2        1
45645   97        1        1
45645   97        2        2
45645   97        2        2
45645   97        2        2
45645   97        2        2
45645   97        2        2

1 个答案:

答案 0 :(得分:1)

可以使用Row_NumberCASE声明

来完成

'1'一次在第一条记录中 ,如果您想订购,请查找我用datekey,pointkey列订购结果的第一条记录使用其他列的结果然后在Order by

中使用它
SELECT datekey,
       pointkey,
       CASE WHEN t_key = 1 AND Row_number()OVER(Partition by datekey,pointkey ORDER BY (select null)) = 1 THEN 1 ELSE 2 END AS filter_key,
       t_key
FROM   Yourtable 

如果上述查询的结果足够好,请运行以下更新查询

;with cte as
(
SELECT datekey,
       pointkey,
       filter_key,
       CASE WHEN t_key = 1 AND Row_number()OVER(Partition by datekey,pointkey ORDER BY (select null)) = 1 THEN 1 ELSE 2 END AS new_filter_key,
       t_key
FROM   Yourtable  
)
update cte set filter_key = new_filter_key