-4
ID  QuestionNo  AnswerPercent
1    15          10  
1    16          10  
1    17          20
1    18          25
2    15          30
2    16          0
2    17          15
2    18          25

输出

ID  QuestionNo  AnswerPercent
1    15          10  
1    16          30  
1    17          20
1    18          25
2    15          30
2    16          15
2    17          15
2    18          25

对于每个 ID,问题 16 和 17 的答案百分比需要合并为 16。对于某些 ID,可能没有任何 16 或 17 个问题编号。

任何人都可以帮我解决这个问题。谢谢!。

4

3 回答 3

2

我相信这就是您所追求的,UPDATE带有JOIN一个子查询:

UPDATE A
SET A.AnswerPercent = B.AnswerPercent
FROM YourTable A
JOIN (SELECT ID, SUM(AnswerPercent)'AnswerPercent'
      FROM YourTable
      WHERE QuestionNo IN ('16','17')
      GROUP BY ID
     )B
ON A.ID = B.ID
WHERE A.QuestionNo = '16'

演示:SQL 小提琴

于 2013-07-10T13:53:45.737 回答
1

尝试添加表两次...表别名为a除问题 17 之外的所有行,表别名为b问题 17 的行

Select a.Id, a.QuestionNo,
   a.AnswerPercent + 
       case A.QuestionNo When 16 
       then coalesce(b.AnswerPercent, 0) End 
       else 0 End AnswerPercent
From table a 
   left Join table b 
     on a.id = b.Id 
       And a.QuestionNo != 17
       And b.QuestionNo = 17

如果您只想更新现有表,那么您需要更新和删除。

update a set 
    AnswerPercent = a.AnswerPercent + 
      IsNull(b.AnswerPercent, 0)
from table a 
   left Join table b  
     on a.id = b.Id 
       And a.QuestionNo = 16
       And b.QuestionNo = 17

 --and then ... 

 delete table where QuestionNo = 17
于 2013-07-10T13:57:35.020 回答
0
with aaa as(
select sum(AnswerPercent) as AnswerPercent,ID
from Table
where QuestionNo in (16,17)
group by ID)

select * from Table where QuestionNo <> 16
union
select ID, 16, sum
from aaa
order by ID,AnswerPercent
于 2013-07-10T13:54:09.457 回答