首页 > 解决方案 > 根据某列的值从不同行中选择值

问题描述

例如我有这样的数据

    date     |  col_1 |   Col_2 |   Col_3   | Col_4
---------------------------------------------
 20021   |   1    |   a     |   null    |   a
 20022   |   2    |   a     |   null    |   a
 20023   |   3    |   a     |   null    |   a
 20024   |   4    |   a     |   4.5     |   a
 20031   |   1    |   a     |   11      |   b
 20032   |   2    |   a     |   2       |   b
 20033   |   3    |   a     |   9       |   b
 20034   |   4    |   a     |   11      |   b

我需要的是当 Col_3 中的值为 null 并且 Col_1 不是 4 时,然后选择 Col_3 中 Col_1 = 4 的值,它们具有相同的

我尝试使用这个案例陈述:

select col_2, date, col_1, col_4,
   case when col_3 is null and col_1 != 1
     then (select col_3 from table s where s.date = 4
           and s.col_1= seg.col_1 and s.col_4= seg.col_4
           and left(s.date,4) = left(seg.date,4))
    else seg.col_3
  end as col_3
from table seg

但由于某种原因,它没有做我需要它做的事情,我需要它来改变上表的结果,变成这样:

    date     |  col_1 |   Col_2 |   Col_3   | Col_4
---------------------------------------------
 20021   |   1    |   a     |   4.5    |   a
 20022   |   2    |   a     |   4.5    |   a
 20023   |   3    |   a     |   4.5    |   a
 20024   |   4    |   a     |   4.5     |   a
 20031   |   1    |   a     |   11      |   b
 20032   |   2    |   a     |   2       |   b
 20033   |   3    |   a     |   9       |   b
 20034   |   4    |   a     |   11      |   b

标签: sqlsql-server

解决方案


也许使用一个OUTER APPLY(或者CROSS APPLY如果你可以保证第 4 季度在那里)总是有每个 col4 每年可用的第 4 季度,然后在你必须的地方使用它。

select col_2, date, col_1, col_4,
   case when col_3 is null and col_1 != 4
     then backfill.col_3
    else seg.col_3
  end as col_3
from table seg
outer apply (select col_3 from table where col_1 = 4 and left(date,4) = left(seg.date,4)) and col_4 = seg.col_4) backfill

如果您宁愿坚持使用 CASE,这应该可以。

case when col_3 is null and col_1 != 4
     then (select col_3 from table s where s.col_1 = 4 
           and s.col_4 = seg.col_4
           and left(s.date,4) = left(seg.date,4))
    else seg.col_3

推荐阅读