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

时间:2013-05-15 11:06:47

标签: sql sql-server join group-by cursor

我有一个具有以下值的表

 sno     package  id
 66      250     111
 66       0      100
 66       0      99
 66       0      88
 67      270     225
 67      267     111
 67      0       35
 68      230     111
 68      225     250
 68      0       210

现在我想要的是package的值为0的地方,包的值为id为111,即66:250,67:267,68:230

以下结果

sno    value     id    
66     250      111
66     250      100
66     250      99
66     250      88
67     270      225
67     267      111
67     267      35  
68     230      111
68     225      250
68     230      230
68     230      210

我正在应用一些像

这样的查询
select sno, case age when 0 then (select age from table1 where id=111 )
                     else 1 end as age, ID from table1

这个内部子查询提供了多个值,我也不能使用sno作为硬编码。 怎么做?请使用groupby clause或某些joinscursor帮助。

由于

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT sno
      , CASE WHEN age = 0 
             THEN (SELECT age FROM table1 t1 
                    WHERE t1.id=111
                      AND t1.sno = t2.sno ) 
             ELSE age END AS age
      ,ID 
FROM table1 t2

或者您也可以使用自联接(我认为这样更好):

SELECT t1.sno
       , CASE WHEN t1.age = 0 
              THEN t2.age 
              ELSE t1.age END AS age
      ,t1.ID 
FROM table1 t1
JOIN table1 t2
  ON t1.sno = t2.sno
 AND t2.id=111;

输出:

╔═════╦═════╦═════╗
║ SNO ║ AGE ║ ID  ║
╠═════╬═════╬═════╣
║  66 ║ 250 ║ 111 ║
║  66 ║ 250 ║ 100 ║
║  66 ║ 250 ║  99 ║
║  66 ║ 250 ║  88 ║
║  66 ║ 250 ║  87 ║
║  67 ║ 270 ║ 225 ║
║  67 ║ 267 ║ 111 ║
║  67 ║ 267 ║  35 ║
║  68 ║ 230 ║ 111 ║
║  68 ║ 225 ║ 250 ║
║  68 ║ 230 ║ 230 ║
╚═════╩═════╩═════╝

See this SQLFiddle

答案 1 :(得分:0)

当年龄为0时,我会将此视为表中的“查找”年龄。为此,我将查询结构为:

select sno, (case when t.age = 0 then lookup.age else t.age end) as age, id
from table1 t left outer join
     (select *
      from t
      where id = 111
     ) lookup
     on t.sno = lookup.sno;

left outer join是为了确保在没有“111”行的情况下不会丢失任何行。子查询要清楚查询中的逻辑。