简体   繁体   中英

Disassemble string, group, and reconstruct in Oracle SQL

So here is what a sample of my data look like:

ID     | Amount
1111-1 |  5  
1111-1 | -5
1111-2 |  5
1111-2 | -5
12R-1  |  8
12R-1  | -8
12R-3  |  8
12R-3  | -8
54A73-1|  2
54A73-1| -2
54A73-2|  2
54A73-2| -1

What I want to do is group by the string in the ID column before the dash, and find the group of IDs that have a sum of zero. The kicker is that after I find which group of IDs sum to zero, I want to add back the dash and number following the dash.

Here is what I hope the solution to look like:

ID     | Amount
1111-1 |  5  
1111-1 | -5
1111-2 |  5
1111-2 | -5
12R-1  |  8
12R-1  | -8
12R-3  |  8
12R-3  | -8

Notice how the IDs starting with 54A73 are not there anymore, its because the sum of their Amounts is not equal to zero.

Any help solving this questions would be much appreciated!

Here's one option joining the table back to itself after grouping by the beginning part of the id field using left and locate :

MySQL Version

select id, amount
from yourtable t 
   join (
    select left(id, locate('-', id)-1) shortid
    from yourtable
    group by left(id, locate('-', id)-1)
    having sum(amount) = 0
     ) t2 on left(t.id, locate('-', t.id)-1) = t2.shortid     

Oracle Version

select id, amount
from yourtable t 
   join (
    select substr(id, 0, instr(id,'-')-1) shortid
    from yourtable
    group by substr(id, 0, instr(id,'-')-1) 
    having sum(amount) = 0
     ) t2 on substr(t.id, 0, instr(t.id,'-')-1) = t2.shortid     

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