简体   繁体   中英

add record in SQL based on last character of a field

I have a field in sql that contains a 1 or 0 at the end. What I am trying to do is if the field has a 1 at the end but no corresponding 0 I would like to add that record.

3 different examples

Field value

  • Data1 ( I would like to add another record containing Data0)

  • Data0 ( I would like to add another record containing Data1)

  • Data0 and Data1 both exists in table ( Do nothing )
insert into test(col, another_column_1,...,another_column_n)
select substr(col,1, length(col)-1) ||   --this is the base value
        max(mod(substr(col,length(col),length(col))+1,2)) --this is the termination (0 or 1)
        as col ,
        max(another_column_1),
        ...
        max(another_column_n)
from test
where substr(col,length(col),length(col)) between '0' and '1'
group by substr(col,1, length(col)-1)
having count(*)=1;

you can see test here

Updated for Oracle

If I understood your question correctly, you can use the LIKE operator.

You can do something like:

(field like '%1' or field like '%0') and not field like '%0%1'

But generally, SQL is not suitable for text processing. This LIKE thing is pretty much the most advanced text processing feature in SQL.

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