2012-01-11 22 views
2

我在sql中包含1或0的字段。我想要做的是如果该字段最后有1,但没有相应的0我想添加该记录。根据字段的最后一个字符在SQL中添加记录

3个不同的例子

字段值

  • 数据1(我想添加包含数据0另一个记录)

  • 数据0(我想添加包含数据1另一记录)

  • Data0和Data1都存在于表中(什么也不做)
+0

那些行与另一列相关的或你必须在表中只有两行? – ivowiblo 2012-01-11 14:53:42

+3

Oooh my g ...有多少[NF](https://en.wikipedia.org/wiki/Database_normalization#Normal_forms)你是否立刻破门而入? – greut 2012-01-11 14:55:48

+0

做的行有固定的长度吗? – 2012-01-11 14:56:12

回答

1
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; 

你可以看到测试here

更新了甲骨文

+0

它给了我一个不够的值错误。我应该在Oracle之前提到过 – user1143409 2012-01-11 15:37:37

+0

这对oracle来说可以,但是应该使用substr。你应该插入其他列。我会在几秒钟内更新答案。 – 2012-01-11 15:40:32

+0

好吧,这是我插入到best_plan_totals(描述)select substr(描述,1,长度(描述)-1)|| (*)= 1的substr(description,1,length(description)-1)的best_plan_totals组中的max(mod(substr(description,length(description),length(description))+ 1,2) – user1143409 2012-01-11 15:59:09

0

如果我正确理解您的问题,则可以使用LIKE运算符。

你可以这样做:

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

但是总体来说,SQL是不适合的文本处理。这LIKE东西几乎是SQL中最先进的文本处理功能。

+0

这导致返回每一行 – user1143409 2012-01-11 15:15:15

+0

我基本上试图为每个唯一描述字段有2个记录。一个在末尾有1,另一个在末尾有一个0 – user1143409 2012-01-11 15:17:09

+0

此查询不应返回字段类似于“abc0abc1”的行。 – 2012-01-11 15:19:05

相关问题