简体   繁体   中英

SQL Query to sum two rows

I have a query which returns result like below:

GRP_NAME   ACCT_COUNT
CLS         1
CMC         2
CNV         7
CON        11
COR        16

You can assume it like

SELECT GRP_NAME, ACCT_COUNT from A;

Now my requirement is, for first and second row, I wanna show them together and I also want to add their ACCT_COUNT . So result will be something like this

CLS-CMC      3
CNV          7
CON         11
COR         16

I want to do this in my SQL query itself. Can you please suggest!! Thanks.

Use a case statement and aggregates. This assumes that it is always CLS 1 and CMC 2 that you want to group together. if there is some other grouping mechanism in the database then we may be able to join to it and group based on it however, that information hasn't been provided in the original question. So... given what we know... this is how it could be done.

SELECT case WHEN grp_name in ('CLS','CMC')  
    then 'CLS-CMC' 
    else grp_name end as GRP_NAME, 
    sum(acct_Count) as Acct_Count
FROM A
GROUP BY case WHEN grp_name in ('CLS','CMC') 
     then 'CLS-CMC' 
     else grp_name end

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