将一列的值复制到另一列的另一列

时间:2018-05-31 17:26:34

标签: sql sql-server sql-server-2008

我需要在second_value列中创建一个select,当类型为'B'时,会复制first_value列的值

换句话说,只有当类型为“B”时,才在列中放置相同的值:first_value列中的first_value。 类型“C”不会在第二个值列中放置任何内容。 实施例

id  descripcion   type   first_value    second_value
1   grain          A     1000   
2   beans          B                    1000 (copied from the first_value column)
3   sugar          C     2000

我正在尝试这样的事情,但我没有获得理想的结果

 SELECT id, description, type, firt_value, 
     CASE WHEN type = 'B' THEN first_value end second_value

有可能这样做吗?我该怎么做?

4 个答案:

答案 0 :(得分:0)

我猜你几乎就在那里。当类型为CASE ... END时,您只需要另一个first_value归零'B'

SELECT id,
       description,
       type,
       CASE
         WHEN type = 'B'
           THEN NULL
         ELSE
           first_value
       END first_value,
       CASE
         WHEN type = 'B'
           THEN first_value
         ELSE
           second_value
       END second_value;

答案 1 :(得分:0)

SELECT id, description, type,  
    CASE WHEN type = 'A' THEN first_value ELSE null end first_value,
CASE WHEN type = 'B' THEN first_value ELSE null end second_value 

答案 2 :(得分:0)

您需要case表达subquery来获取上一行:

select *, (case when type = 'B'
                then (select top 1 t1.first_value 
                      from table t1
                      where t1.id < t.id
                      order by t1.id desc
                     ) else first_value
           end) as second_value
from table t; 

答案 3 :(得分:0)

您需要在查询中添加Else条件

SELECT id, description, type,
CASE WHEN type = 'A' THEN first_value
 Else null end as first_value
 CASE WHEN type = 'B' THEN first_value
 Else second_value end as second_value