简体   繁体   中英

Distribute one row of data to two rows in SQL

I have the table below. Is there a good way to regroup them such that group 'a+b' gets double counted and added to group 'a' and 'b'

Group Amount
  a     100
  b     200
  c     300
 a+b    400

The result would be:

Group Amount
  a    500
  b    600
  c    300

This is hideous, but you could do a subquery for matching groups.

SELECT GroupId,
Amount + ISNULL(
  (SELECT SUM(Amount) FROM MyGroups t2
   WHERE t2.GroupId <> t1.GroupId
   AND t2.GroupId LIKE '%' + t1.GroupId + '%'), 0)
FROM MyGroups t1
WHERE t1.GroupId NOT LIKE '%+%'

http://sqlfiddle.com/#!3/50214/8

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