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个问题编号。
任何人都可以帮助我。谢谢!
答案 0 :(得分: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 Fiddle
答案 1 :(得分: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
答案 2 :(得分: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