需要计算借方的运行余额

时间:2017-02-23 01:06:16

标签: sql sql-server-2008

我正在为一个帐户项目工作,我已经停留在一个地方。

表格是借方

 alert("Welcome again " + user);

我的结束输出在所有计算之后应该是

 <!DOCTYPE html>
 <html>
 <head>
 <script>

    function setCookie(cname,cvalue,exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires=" + d.toGMTString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
    }

   function getCookie(cname) {
      var name = cname + "=";
      var decodedCookie = decodeURIComponent(document.cookie);
      var ca = decodedCookie.split(';');
      for(var i = 0; i < ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0) == ' ') {
        c = c.substring(1);
      }
    if (c.indexOf(name) == 0) {
        return c.substring(name.length, c.length);
    }
   }
   return "";
}

  function checkCookie() {
   var user=getCookie("username");
   if (user != "") {
       alert("Welcome again " + user);  
   } else {
      user = prompt("Please enter your name:","");
      if (user != "" && user != null) {
          setCookie("username", user, 30);
      }
   }
 }

  </script>
  <?php echo  "Welcome back : ".$user;?>
  </head>
  <body onload="checkCookie()">
  </body>
  </html>

如果我们尝试(总和A +总和B +总和C) - 信用,数字将是相同的但它将在A列中出现,所以在我认为上述计算之后我必须应用计算。

有谁知道如何实现这一目标。

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

SQL Server仅支持版本MSSQL 2012中的分析函数SUM() OVER,因此对于2008,这可能是查询结果的一种方法:

WITH table_name AS
( 
    SELECT 1 ID, 000.00 Debit, 900.00 Credit, 0       a, 0       b, 1000.00     c UNION ALL
    SELECT 2 ID, 450.00 Debit, 425.00 Credit, 0       a, 450.00  b, 0   c UNION ALL
    SELECT 3 ID, 500.00 Debit, 490.00 Credit, 500.00  a, 0       b, 0   c UNION ALL
    SELECT 4 ID, 600.00 Debit, 599.00 Credit, 600.00  a, 0       b, 0   c UNION ALL
    SELECT 5 ID, 748.00 Debit, 700.00 Credit, 0       a, 748.00  b, 0   c 
)
, 
sum_credit AS
(
    SELECT SUM(credit) sumcredit 
    FROM table_name
)
SELECT t.id, t.debit, t.credit, 
    CASE WHEN a = 0
            OR ( (SELECT COALESCE(SUM(a + b + c), 0) FROM table_name WHERE id < t.id)
                + a - sc.sumcredit < 0
            )
        THEN 0 
        ELSE (SELECT COALESCE(SUM(a + b + c), 0) FROM table_name WHERE id < t.id)
            + a - sc.sumcredit 
        END a,
    CASE WHEN b = 0
            OR ( (SELECT COALESCE(SUM(a + b + c), 0) FROM table_name WHERE id < t.id)
                + a + b - sc.sumcredit < 0
            )
        THEN 0 
        ELSE (SELECT COALESCE(SUM(a + b + c), 0) FROM table_name WHERE id < t.id)
            + a + b - sc.sumcredit 
        END b,
    CASE WHEN c = 0 
            OR ( (SELECT COALESCE(SUM(a + b + c), 0) FROM table_name WHERE id < t.id)
                + a + b + c - sc.sumcredit < 0
            )
        THEN 0 
        ELSE (SELECT COALESCE(SUM(a + b + c), 0) FROM table_name WHERE id < t.id)
            + a + b + c - sc.sumcredit 
        END c
FROM 
    table_name t
CROSS JOIN 
    sum_credit sc;