简体   繁体   中英

SQL merge row values in a column

TABLE 1

CODE VALUE
AA 21
AA 32
AB 24
AC 22
AA 42
AC 20
AD 27
AD 28
AE 29
AF 31
AG 45
AE 51
AH 33

TABLE 2

CODE KEY
AA 1
AB 2
AC 3
AD 4
AE 5
AF 6
AG 7
AH 8

Here i want to transform the table in such a way that AB value is summed to AA without effecting its key similarly AG's value has to be summed with AD without changing its key as below. Table 1 can have multiple values for a single code. pls help or tell me the approach.

CODE VALUE KEY
AA 119 1
AC 22 3
AD 100 4
AE 29 5
AF 31 6
AH 33 8

Use a CASE expression in TABLE1 to merge the codes that you want and aggregate and join to TABLE2 :

SELECT t1.code, t1.value, t2.key
FROM (
  SELECT CASE code 
           WHEN 'AB' THEN 'AA' 
           WHEN 'AG' THEN 'AD' 
           ELSE code 
         END code, 
         SUM(value) "value"
  FROM table1
  GROUP BY 1
) t1 INNER JOIN table2 t2
ON t2.code = t1.code
ORDER BY t1.code;

See the demo .

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