Re: [MSSQL] 算10題相加平均值
declare @t table(t1 int, t2 int, t3 int, t4 int
, sum decimal, count decimal, avg decimal(5,2))
insert @t(t1,t2,t3,t4) values(1,2,3,4)
insert @t(t1,t2,t3,t4) values(1,2,1,4)
insert @t(t1,t2,t3,t4) values(1,1,3,4)
insert @t(t1,t2,t3,t4) values(1,2,3,1)
declare @sum decimal, @count decimal
update @t set
@sum=0, @count=0,
@sum = @sum+ case when t1<>1 then t1 else 0 end,
@sum = @sum+ case when t2<>1 then t2 else 0 end,
@sum = @sum+ case when t3<>1 then t3 else 0 end,
@sum = @sum+ case when t4<>1 then t4 else 0 end,
@count = @count+ case when t1<>1 then 1 else 0 end,
@count = @count+ case when t2<>1 then 1 else 0 end,
@count = @count+ case when t3<>1 then 1 else 0 end,
@count = @count+ case when t4<>1 then 1 else 0 end,
sum=@sum, count=@count, avg=@sum/@count
from @t
select * from @t
我覺得 table設計不是很好,連 PK都沒有...
※ 引述《bkk (.....)》之銘言:
: 目前在做一個問卷分數的計算
: 問卷一共有10題 分數個別是
: 非常不滿意:1
: 不滿意:2
: 尚可:3
: 滿意:4
: 非常滿意:5
: 資料庫欄位則有題目1到題目10以及平均分數
: 我現在想要把10題的分數加起來後算平均值
: 目前的SQL語法如下
: UPDATE dbo.Q_問卷一 set 平均分數 =
: (題目1+ 題目2+題目3+題目4+題目5+題目6+題目7+題目8+題目9+題目10)/10
: 問題來了 現在我要把分數為1的題目去掉 不納入平均值計算
: 例如:題目1為1 那平均分數就是 (題目2+到題目10)/9
: 題目1跟2為1 那平均分數就是 (題目3+到題目10)/8
: 我有認真想過 不過實在是沒概念
: 我甚至想說用土法煉鋼的方式 寫好幾百種當題目x=1的條件去判斷(實在是蠢的可以= =)
: 拜託大家幫個忙了 感謝!!!
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 220.130.152.24
推
11/10 11:46, , 1F
11/10 11:46, 1F
→
11/10 21:50, , 2F
11/10 21:50, 2F
推
11/11 00:08, , 3F
11/11 00:08, 3F
→
11/11 09:14, , 4F
11/11 09:14, 4F
→
11/11 19:57, , 5F
11/11 19:57, 5F
我覺得設計良好的資料表在寫程式的時候會有提示效果,
設計資料表這步驟會強迫我在寫程式之前先想好怎麼寫。
這個問題我想了幾個方法都不太順手,
後來發現是少了pk,習慣到失去還沒馬上發覺…
一個問卷題目存在一個欄位,
這樣設計的資料表也不夠泛用,換份問卷又要重開一次。
※ 編輯: grence 來自: 123.194.23.13 (11/12 20:18)
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):