SQL Summing and Grouping
How can I modify this query to display what it already does but also include the total SUM either in a separate row or column of InvPayAmnt per each select which has a unique CardName?
SELECT IdEntry,
DocNum,
'MICHIGAN' + CardCode,
QUOTENAME(CardName,'"'),
Convert(Decimal(10,2),InvPayAmnt),
CONVERT(VARCHAR(10), T5.PmntDate,101),
NumAtCard,
PymMeth,
'Objtype' = CASE WHEN Objtype = 19 THEN 'CREDIT' ELSE 'INVOICE' END
FROM MICHIGAN.dbo.PWZ3
INNER JOIN MICHIGAN.dbo.OPWZ T5 ON T5.IdNumber = IdEntry
WHERE T5.PmntDate = '4/1/2011'
AND T5.Canceled = 'N'
AND Checked = 'Y'
UNION
SELECT IdEntry,
DocNum,
开发者_JAVA技巧 'BEN' + CardCode,
QUOTENAME(CardName,'"'),
Convert(Decimal(10,2),InvPayAmnt),
CONVERT(VARCHAR(10),T5.PmntDate,101),
NumAtCard,
PymMeth,
'Objtype' = CASE WHEN Objtype = 19 THEN 'CREDIT' ELSE 'INVOICE' END
FROM BENSALEM.dbo.PWZ3
INNER JOIN BENSALEM.dbo.OPWZ T5 ON T5.IdNumber = IdEntry
WHERE T5.PmntDate = '4/1/2011'
AND T5.Canceled = 'N'
AND Checked = 'Y'
ORDER By 3
----------------CURRENT OUTPUT -----------------------------------
791 1608424 BENV5649 "K&C VENDOR" 1235.01 04/01/2011 10-111 EFT-JP INVOICE
791 1608425 BENV5649 "K&C VENDOR" 215.00 04/01/2011 5801 EFT-JP INVOICE
148 600913 MICHIGANV0077 "Tendercare" 18.03 04/01/2011 10/29 PM2 INVOICE
148 600916 MICHIGANV0077 "Tendercare" 48.08 04/01/2011 10/9 PM2 INVOICE
----------------REQUIRED OUTPUT-----------------------------------
791 1608424 BENV5649 "K&C VENDOR" 1450.01 04/01/2011 10-111 EFT-JP SUM
791 1608424 BENV5649 "K&C VENDOR" 1235.01 04/01/2011 10-111 EFT-JP INVOICE
791 1608425 BENV5649 "K&C VENDOR" 215.00 04/01/2011 5801 EFT-JP INVOICE
148 600913 MICHIGANV0077 "Tendercare" 66.11 04/01/2011 10/29 PM2 SUM
148 600913 MICHIGANV0077 "Tendercare" 18.03 04/01/2011 10/29 PM2 INVOICE
148 600916 MICHIGANV0077 "Tendercare" 48.08 04/01/2011 10/9 PM2 INVOICE
It would also work if the sum was placed in the last column, either way would be fine.
Because of the convert()
call I assume you are using SQL Server.
If you have a fairly recent version (2005 or later), the following should work:
SELECT ....
sum(InvPayAmnt) over (partition by CardName) as payment_sum
FROM ....
精彩评论