SQL求和和分组

时间:2011-05-04 12:45:40

标签: sql sum

如何修改此查询以显示它已经执行的操作,但是还要在每个具有唯一CardName的选择的InvPayAmnt的单独行或列中包含总SUM?

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, 
       '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

如果将总和放在最后一列中,它也会有效,无论哪种方式都没问题。

1 个答案:

答案 0 :(得分:1)

由于convert()调用,我假设您使用的是SQL Server。

如果你有一个相当新的版本(2005或更高版本),以下应该有效:

SELECT ....
       sum(InvPayAmnt) over (partition by CardName) as payment_sum
FROM ....