[英]SQL SELECT How to find a substring number in between two columns?
給定一個搜索字符串(部分數字)和一個具有兩個varchar列FROM_NUMBER和TO_NUMBER的表,我想選擇包含搜索字符串的行,該字符串的數字介於FROM_NUMBER和TO_NUMBER(含)之間。
我知道像'%xxx%',但這僅用於匹配列。
示例:我有下表NUMBER_RANGE
| ID | PREFIX | FROM_NUMBER | TO_NUMBER |
|----|--------|-------------|------------|
| 1 | +1 | 4081234500 | 4081234599 |
| 2 | +61 | 267222000 | 267222009 |
| 3 | +81 | 11812205 | 11812205 |
| 4 | +61 | 240859600 | 240859600 |
說,給定“ 4501”,它應該返回行1,因為“ 4501”是數字“ 4081234501”的子字符串,介於“ 4081234500”和“ 4081234599”之間
給定“ 4081234500”或“ 4081234509”或“ 4081234599”,它應返回第1行。
給定“ 408”,它將返回第1行和第4行。
如何構造具有正確WHERE條件的SQL SELECT語句以返回所需的記錄?
是否可以在不進行移動的情況下將FROM_NUMBER擴展到TO_NUMBER的情況下進行搜索(因為該范圍內可能有1000個數字,並且處理時間太長)?
謝謝。
尋找拳頭樣品..您只需將字符串轉換為數字
select 'OK'
from dual
where 4501 between
CAST(right('4081234500', length('4501')) AS INT)
AND CAST(right('4081234599', length('4501')) AS INT)
;
對於您的表,假設my_value包含“ 4501”
select id
from my_table
where cast(my_value) between
cast(right(FROM_NUMBER, length(my_value)) AS INT)
AND CAST(right(TO_NUMBER, length(my_value)) AS INT)
對於第二個示例,您應該使用字符串的左側部分而不是右側,並使用OR來使用兩個條件togheter
據我了解您的問題,我進行了查詢以查找確切數字是否作為子字符串出現在您的列中,或者給出的數字是否出現在您列的最后匹配數字中。 即,如果提供的數字的長度為2,則將考慮從from和to的最后兩位數字進行范圍搜索。
您可以嘗試以下查詢:
YOUR_NUMBER = 4501
SELECT * FROM TABLE
WHERE FROM_NUMBER LIKE '%' || YOUR_NUMBER || '%'
OR TO_NUMBER LIKE '%' || YOUR_NUMBER || '%'
OR YOUR_NUMBER
BETWEEN MOD(FROM_NUMBER, POWER(10, LENGTH(YOUR_NUMBER)))
AND MOD(TO_NUMBER, POWER(10, LENGTH(YOUR_NUMBER)));
干杯!!
該查詢看起來很復雜,但事實並非如此。 這個想法是將數字切成若干個圖案長度的塊,並與圖案進行比較,就像一個人一樣:
with
s(str) as (select 81220 from dual),
a as (
select id, str, length(str) ls, from_number fn, to_number tn,
lpad(from_number, length(to_number), '0') s1, to_char(to_number) s2
from number_range join s on length(to_number) >= length(str)),
c(col, id, str, ls, s1, s2, sb1, sb2, match) as (
select 1, id, str, ls, s1, s2, substr(s1, 1, ls), substr(s2, 1, ls),
case when str between substr(s1, 1, ls)
and substr(s2, 1, ls) then 1 end
from a
union all
select col + 1, id, str, ls, s1, s2, substr(s1, col + 1, ls), substr(s2, col + 1, ls),
case when str between substr(s1, col + 1, ls)
and substr(s2, col + 1, ls) then 1 end
from c
where col <= length(s1) - ls and match is null )
select id, str, sb1, sb2, prefix, from_number, to_number
from c join number_range using (id)
where match = 1 order by id, col;
s
要查找的值(您可以在此處使用並集輸入多個值)
a
-在從表中的數據from_number
被lpadded用零到to_number
的長度
c
是遞歸查詢。 我從兩個數字中切出第一個塊,然后與模式進行比較。 如果在分析之間停止( and match is null
則對此負責)。 否則,它將繼續。
最后,我將結果(如果找到任何內容)與原始數據結合在一起,並顯示字符串的哪一部分相對應。 如果有更多行,並且您希望將它們全部刪除and match is null
,則此查詢查找每行的第一次出現。 希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.