简体   繁体   中英

Group by two columns using Sum on one column

I need to sum "Total" column by "Account" and by "Month", I'm expecting a single line per Account - Month combination

SELECT 
'NPI' as Company, SYACTFIL_SQL.acc`enter code here`t_desc as Description , 
left(GLTRXFIL_SQL.mn_no,5) + '-' + left(GLTRXFIL_SQL.sb_no,4) as Account,   
right(left(GLTRXFIL_SQL.trx_dt,6),2) as Month, SUM(GLTRXFIL_SQL.trx_amt) as Total

FROM Data.dbo.GLTRXFIL_SQL GLTRXFIL_SQL,Data.dbo.SYACTFIL_SQL SYACTFIL_SQL

WHERE GLTRXFIL_SQL.mn_no = SYACTFIL_SQL.mn_no AND 
GLTRXFIL_SQL.sb_no`enter code here` = SYACTFIL_SQL.sb_no AND 
(GLTRXFIL_SQL.trx_dt>=20130101) AND (GLTRXFIL_SQL.trx_dt<=20130630) AND
SYACTFIL_SQL.fin_stmt_tp = 'P'

Group by SYACTFIL_SQL.acct_desc, GLTRXFIL_SQL.trx_dt, GLTRXFIL_SQL.mn_no,GLTRXFIL_SQL.sb_no

Order by  GLTRXFIL_SQL.mn_no,GLTRXFIL_SQL.trx_dt;

Assuming 1 account description per account, and without seeing table structure to know better, this should work:

SELECT   'NPI' as Company
        , b.acct_desc as Description 
        , left(a.mn_no,5) + '-' + left(a.sb_no,4) as Account
        , right(left(a.trx_dt,6),2) as MONTH
        , SUM(a.trx_amt) as Total
FROM Data.dbo.GLTRXFIL_SQL GLTRXFIL_SQL a
JOIN Data.dbo.SYACTFIL_SQL SYACTFIL_SQL b
     ON   a.mn_no = b.mn_no 
     AND  a.sb_no = b.sb_no 
WHERE   a.trx_dt>=20130101
    AND a.trx_dt<=20130630 
    AND b.fin_stmt_tp = 'P'
GROUP BY  b.acct_desc
        , left(a.mn_no,5) + '-' + left(a.sb_no,4)
        , right(left(a.trx_dt,6),2)
ORDER BY  left(a.mn_no,5) + '-' + left(a.sb_no,4)
        , right(left(a.trx_dt,6),2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM