我在尝试从CASE语句中计算运行总计时遇到问题。
我有两个表@report
和@question
以及两个变量@countCurrent
和@countSuggested
。
根据@report
表中的数字与静态值或@question
表中的值进行比较,我需要增加@countCurrent
或@countSuggested
。< / p>
这是我到目前为止所得到的,但不是在任何一列中得到5的组合,我只得到0/1。我认为这是JOIN的一部分,但我看不清楚。
declare @MinSuccessRate float,
@countCurrent int,
@countSuggested int
declare @report table
(
intID int identity(1,1),
intReportID int,
intParticipantID int,
acceptable float,
optimum float
)
insert @report
select 1,1,.25,.75 union all
select 1,2,.45,.75 union all
select 1,3,.35,.75 union all
select 1,4,.55,.75 union all
select 1,5,.65,.75
declare @question table
(
intID int identity(1,1),
intParticipantID int,
answer float
)
insert @question
select 1,35 union all
select 1,55 union all
select 1,65 union all
select 1,75 union all
select 1,85
SET @MinSuccessRate=0.75
SET @countCurrent=0
SET @countSuggested=0
UPDATE @report
SET @countCurrent=
CASE WHEN acceptable>=@MinSuccessRate
THEN @countCurrent+1
ELSE 0
END,
@countSuggested=
CASE WHEN optimum*100 >=q.answer
THEN @countSuggested+1
ELSE 0
END
FROM @report pr
INNER JOIN @question q
ON pr.intParticipantID=q.intParticipantID
WHERE pr.intReportID=1
select @countCurrent [Current],@countSuggested [Suggested]
提前致谢!
答案 0 :(得分:1)
在多表UPDATE
中,每个目标记录最多可以更新一次(无论连接返回多少次)。
但是,您根本不需要UPDATE
:
SELECT @countCurrent =
SUM
(
CASE
WHEN acceptable >= @MinSuccessRate
THEN
1
ELSE
0
END
),
@countSuggested =
SUM
(
CASE
WHEN optimum * 100 >= q.answer
THEN
1
ELSE
0
END
)
FROM @report pr
JOIN @question q
ON q.intParticipantID = pr.intParticipantID
WHERE pr.intReportID = 1
答案 1 :(得分:0)