如何在ORACLE中选择SUBSTRING

时间:2017-01-26 18:35:19

标签: sql oracle select substring

我需要选择一个子字符串来从表字段中获取连续数字。我的表是:

ORDER_NUM       ORDER_DATE   ORDER_TYPE  LOCATION   SALE_TYPE
10501702315618  08/01/17       43223       1050        18    
105017023186230 21/01/17       43221       1050        230

字段ORDER_NUM生成如下

[LOCATION] + [YY] + [CONSECUTIVE_NUMBER] + [SALE_TYPE]

字段LOCATION和SALE_TYPE的长度可以不同。所以,我的查询是:

SELECT 
SUBSTR(ORDER_NUM,LENGTH (ORDER_TYPE)  + 3,LENGTH (ORDER_NUM)   - LENGTH ( SALE_TYPE ) ),
ORDER_DATE
FROM 
CAT_ORDERS
WHERE 
LOCATION = '1050'
AND SALE_TYPE = '18'

结果是

    SELECT SUBSTR('10501702315618',7,12) from dual
    RESULT: 02315618

指数位置为:

 12345678901234
 10501702315618

如何删除字符串中的SALE_TYPE字符?还有另外一个功能吗?

感谢'!小号

4 个答案:

答案 0 :(得分:4)

您的描述是指位置,因此您的偏移基于订单类型很奇怪。子字符串的长度也需要排除位置和年份的长度:

SUBSTR(ORDER_NUM, LENGTH (LOCATION) + 3,
  LENGTH (ORDER_NUM) - LENGTH(LOCATION) - 2 - LENGTH (SALE_TYPE))

当你从偏移中获得12个字符时,当你只需要6个字符时,实际上只有8个字符可用。

使用您的数据进行演示:

WITH CAT_ORDERS (ORDER_NUN, ORDER_DATE, ORDER_TYPE, LOCATION, SALE_TYPE) AS (
  SELECT 10501702315618, TO_DATE('08/01/17', 'DD/MM/RR'), 43223, 1050, 18 FROM DUAL
  UNION ALL SELECT 105017023186230, TO_DATE('21/01/17', 'DD/MM/RR'), 43221, 1050, 230 FROM DUAL
)
SELECT SUBSTR(ORDER_NUM, LENGTH (LOCATION) + 3,
  LENGTH (ORDER_NUM) - LENGTH(LOCATION) - 2 - LENGTH (SALE_TYPE))
FROM CAT_ORDERS;

023156
023186

您的订单号会复制其他列中的数据,这看起来并不理想。仅存储连续数字'更简单。而是生成整个订单号作为虚拟列。

答案 1 :(得分:2)

这应该从最后删除sale_type字符:

select 
  substr(substr(order_num, 0, length(order_num)-length(sale_type)), length(location) + 3)
from t;

答案 2 :(得分:2)

select  regexp_substr(ORDER_NUM,'^' || LOCATION || '..(.*)' || SALE_TYPE || '$',1,1,'',1)
from    mytable;

因为我们现在知道consecutive_number的长度是固定的(即6):

select  regexp_substr(ORDER_NUM,'^' || LOCATION || '..(.{6})',1,1,'',1)
from    mytable;

select  regexp_substr(ORDER_NUM,'(.{6})' || SALE_TYPE || '$',1,1,'',1)
from    mytable;

答案 3 :(得分:1)

因为我们现在知道static int wc_AesEncrypt(Aes* aes, const byte* inBlock, byte* outBlock) { int ret = 0; #ifdef WOLFSSL_STM32_CUBEMX CRYP_HandleTypeDef hcryp; /* load key into correct registers */ switch(aes->rounds) { case 10: /* 128-bit key */ hcryp.Init.KeySize = CRYP_KEYSIZE_128B; break; case 12: /* 192-bit key */ hcryp.Init.KeySize = CRYP_KEYSIZE_192B; break; case 14: /* 256-bit key */ hcryp.Init.KeySize = CRYP_KEYSIZE_256B; break; default: break; } XMEMSET(&hcryp, 0, sizeof(CRYP_HandleTypeDef)); hcryp.Instance = CRYP; hcryp.Init.DataType = CRYP_DATATYPE_8B; hcryp.Init.pKey = (uint8_t*)aes->key; HAL_CRYP_Init(&hcryp); if (HAL_CRYP_AESECB_Encrypt(&hcryp, (uint8_t*)inBlock, AES_BLOCK_SIZE, outBlock, STM32_HAL_TIMEOUT) != HAL_OK) { ret = WC_TIMEOUT_E; } HAL_CRYP_DeInit(&hcryp); #else ... other non-cubemx support implementations below 的长度是固定的(即6):

consecutive_number

select  substr(ORDER_NUM,length(LOCATION)+3,6)
from    mytable;