一个变量的多个值的总和

时间:2013-05-28 03:33:36

标签: sql count sum dynamic-sql

我想对在循环中保存值的变量求和

这是我的表:

name | pkey | cinema1~cinema10 | total_QTy | total_sales
aaa  |  1   |  100.00 ~ 200.00 |     2     |  300.00
bbb  |  2   |  150.00 ~ 145.00 |     3     |  295.00

total_Qty是在cinema1~cinema10中购买的aaa门票的总和 而且我不知道该怎么做。我只获得了名为bbb cinema10的计票的最后一个值。

请帮帮我。我被困在这里。

以下是获取金额和数量的代码

WHILE ISNULL(@cinema_key, 0) <> 0
BEGIN

    SET @amount = 0


SELECT @amount =(SUM(t1.price)), @qty = (count(t1.cnt))
FROM(
    SELECT 
           (ISNULL(SUM(mctrs.price),0) - (ISNULL(SUM(mctrs.lgu_tax_amount),0) + ISNULL(SUM(mctrs.ordinance_1),0) + ISNULL(SUM(mctrs.ordinance_2),0)+ ISNULL(SUM(mctrs.ordinance_3),0) + ISNULL(SUM(mctrs.ordinance_4),0) ))   AS 'price', 
           count(mctrs.[key]) as 'cnt', mctrs.[key] as ckey
    FROM
    movie_calendar mc
    INNER JOIN
    movie_database md
    ON
    mc.movie_key = md.[key] AND mc.screening_start_date = @tdate
    INNER JOIN
    cinemas c
    ON
    mc.cinema_key = c.[key] AND c.[key] = @cinema_key
    INNER JOIN
    movie_calendar_times mct
    ON
    mct.movie_calendar_key = mc.[key]
    LEFT OUTER JOIN
    movie_calendar_time_reserved_seats mctrs
    ON
    mctrs.movie_calendar_time_key = mct.[key]
    INNER JOIN
    patrons p
    ON
    mctrs.patron_key = p.[key]
    WHERE mctrs.status = 1 AND mctrs.[committed]=1
    GROUP BY p.patron_tag,mctrs.price,P.APPLY_LGU_TAX ,P.LGU_TAX_AMOUNT, mctrs.[key]

)t1

    SET @buffer = 'UPDATE #temptable SET cinema'+CAST(@count AS VARCHAR)+' = '+CAST(ISNULL(sum(@amount),0) AS VARCHAR)+' WHERE [date] = '''+CAST (@tdate AS VARCHAR)+''''

    PRINT (@buffer)
    EXEC(@buffer)
    insert into #tqty(qty) values(@qty)

    DELETE FROM #cinema_list WHERE cinema_key = @cinema_key

    SET @cinema_key = NULL
    SET @cinema_code = NULL

    SELECT TOP 1 @cinema_key = cinema_key, @cinema_code = cinema_code FROM #cinema_list ORDER BY display_order

    SET @count = @count + 1

END /*WHILE CINEMA KEY*/

这是我更新total_Qty和total_sales的代码:

WHILE @count < @cinema_count
BEGIN
    SET @count = @count+1.
    SET @select = @select+'cinema'+CAST(@count AS VARCHAR)+'+' 
END
SET @select = SUBSTRING(@select, 1, LEN(@select) - 1)
SET @buffer = 'UPDATE #temptable SET total_quantity = ' +cast(@qty as varchar) + ', ' + 'total_sales = '+@select 
PRINT @buffer
EXEC( @buffer)

请帮助:3谢谢:)

1 个答案:

答案 0 :(得分:0)

我同意@Dave Collins的说法,这不是最大的数据库设计,但如果您想要简单的答案,则需要将现有值添加到更新中的运行总计中。

改变这个:

SET @buffer = 'UPDATE #temptable SET cinema'+CAST(@count AS VARCHAR)+' = '+CAST(ISNULL(sum(@amount),0) AS VARCHAR)+' WHERE [date] = '''+CAST (@tdate AS VARCHAR)+''''

对此:

SET @buffer = 'UPDATE #temptable SET cinema'+CAST(@count AS VARCHAR)+' = ISNULL(cinema,0) + '+CAST(ISNULL(sum(@amount),0) AS VARCHAR)+' WHERE [date] = '''+CAST (@tdate AS VARCHAR)+''''