【问题标题】:Calculating a total in SQL Server在 SQL Server 中计算总计
【发布时间】:2011-07-22 23:23:05
【问题描述】:

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

根据@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>=@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]

提前致谢!

【问题讨论】:

  • 为什么称它为running total?这是一个简单的总数,除非您或我缺少某些东西。
  • 不,你可能是对的,它不是最好的标题,但幸运的是它已经在下面解决了:)

标签: sql-server-2008


【解决方案1】:

在多表UPDATE中,每条目标记录最多可以更新一次(不管join返回多少次)。

但是,这里根本不需要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

【讨论】:

    【解决方案2】:
    猜你喜欢
    • 2010-10-26
    • 2016-04-20
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多