如何在SQL中获得列的总和?

时间:2015-03-06 06:22:47

标签: sql asp.net sql-server tsql gridview

我写了一个存储过程,当我给Invoice no时,它会返回两个帐户的效果。作为输入参数。

SELECT A.AccountTitle,
       T.VoucherNumber, 
       T.ChequeNumber, 
       T.Particulars, 
       T.DR, 
       T.CR, 
       WU.UserName as Operator
FROM   dbo.Accounts A
INNER JOIN dbo.Transactions T ON T.Account_ID= A.AccountID
INNER JOIN dbo.Web_Users WU ON WU.UserID= T.User_ID
WHERE T.InvoiceNo= @InvoiceNo

输出:

AccountTitle    VoucherNumber   ChequeNumber    Particulars DR  CR  Operator
Conductor       NULL        NULL                New entry   100 0   Irfan
Jamal Acount    NULL        NULL                New entry1  0   100 Irfan

但我最后想要DR和CR字段的总数。

预期输出

 AccountTitle   VoucherNumber   ChequeNumber    Particulars DR  CR  Operator
 Conductor      NULL           NULL             New entry   100 0   Irfan
 Jamal Acount   NULL           NULL             New entry1  0   100 Irfan
                                                    Total   100 100 

2 个答案:

答案 0 :(得分:2)

您可以使用WITH ROLLUP获得所需的结果。见下文:

SELECT
     CASE WHEN GROUPING(T.Particulars)=1 THEN '' ELSE MIN(A.AccountTitle) END AccountTitle,
     CASE WHEN GROUPING(T.Particulars)=1 THEN '' ELSE MIN(T.VoucherNumber) END VoucherNumber,
     CASE WHEN GROUPING(T.Particulars)=1 THEN '' ELSE MIN(T.ChequeNumber) END ChequeNumber,
     CASE WHEN GROUPING(T.Particulars)=1 THEN 'TOTAL' ELSE MIN(T.Particulars) END Particulars, 
     SUM(CONVERT(MONEY,T.DR)) AS DR, 
     SUM(CONVERT(MONEY,T.CR)) AS CR,
     CASE WHEN GROUPING(T.Particulars)=1 THEN '' ELSE WU.UserName END Operator
FROM dbo.Accounts A
INNER JOIN dbo.Transactions T ON T.Account_ID= A.AccountID
INNER JOIN dbo.Web_Users WU ON WU.UserID= T.User_ID
WHERE T.InvoiceNo= @InvoiceNo
GROUP BY WU.UserName WITH ROLLUP

答案 1 :(得分:1)

您可以使用 SUM 功能计算总DR和CR,其他列的空值和 UNION ALL opterator来计算2个select语句的结果集。

这样的事情:

SELECT A.AccountTitle,
       T.VoucherNumber, 
       T.ChequeNumber, 
       T.Particulars, 
       T.DR, 
       T.CR, 
       WU.UserName as Operator
FROM   dbo.Accounts A
INNER JOIN dbo.Transactions T ON T.Account_ID = A.AccountID
INNER JOIN dbo.Web_Users WU   ON WU.UserID= T.User_ID
WHERE  T.InvoiceNo= @InvoiceNo
UNION ALL    
SELECT ''        AS AccountTitle, 
       NULL      AS VoucherNumber, 
       NULL      AS ChequeNumber, 
       'Total'   AS Particulars,
       CAST(SUM(T.DR) AS MONEY) AS DR,
       CAST(SUM(T.CR) AS MONEY) AS CR,
       ''        AS Operator
FROM   dbo.Accounts A
INNER JOIN dbo.Transactions T ON T.Account_ID= A.AccountID
INNER JOIN dbo.Web_Users WU   ON WU.UserID= T.User_ID
WHERE  T.InvoiceNo= @InvoiceNo