2011-07-22 97 views
2

我在尝试从CASE语句中计算运行总数时遇到了问题。 我有两个表@report@question和两个变量@countCurrent@countSuggested在SQL Server中计算总数

根据@report表中与静态值或来自@question表的值进行比较的数字,我需要增加@countCurrent@countSuggested

这是我到目前为止,而不是得到任何一列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>[email protected] 
     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

可能重复的(http://stackoverflow.com/questions/814054/complicated -ql-query-for-a-running-total-column) – JNK

+0

为什么你称它为总运行?这是一个普通的总数,除非有你或我失踪的东西。 – Quassnoi

+0

不,你可能是正确的,它不是最好的标题,但幸运的是它已被解决:) –

回答

1

在多台UPDATE,每个目标记录可以在更新最多一次(无论多少次它被加入返回)。

不过,你不需要UPDATE这里都:[复杂的SQL查询的运行总计列]

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