我写了一个存储过程,当我给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
答案 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