How to check if string ends in date and strip result? - SQL - sql

I'm trying to check whether or not a string ends in a year.
Input:
file_paths
wowefnowinf/wefionwe/wefowoi/2012-02-03
weofnweofn/weoew/2022-03-04
ewpfowe/ewopfew
Desired Output:
wowefnowinf/wefionwe/wefowoi/
weofnweofn/weoew/
ewpfowe/ewopfew
I'm having trouble first detecting that the strings themselves end in a date-format. This is my query:
SELECT CASE WHEN 'wowefnowinf/wefionwe/wefowoi/2012-02-03' LIKE '%/####\-##\-##'
THEN TRUE
ELSE FALSE END AS result
FROM my_table;
I should be getting true for this, but my query returns false. Any help would be appreciated.

In Snowflake you can make use of regexp_like and split_part:
with dummy as (
select 'wowefnowinf/wefionwe/wefowoi/2012-02-03' as file_path
union all
select 'weofnweofn/weoew/2022-03-04'
union all
select 'ewpfowe/ewopfew'
)
select
file_path,
split_part(file_path, '/', -1) as splitted_file_path,
regexp_like(splitted_file_path, '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]') as ends_with_date,
iff(ends_with_date, trim(file_path, splitted_file_path), file_path) as trimmed_file_path
from dummy;
Output:

Related

teradata - invalid select expression list

Trying to make a select query on teradata, but i get this message error:
syntax error: invalid select expression list
I can't fix it. How can I formulate the query appropriately?
SELECT BILS01_GRADO, BILS01_CODICE_COM, BILS01_PROT, BILS01_PROG_OGG_IMP,BILS01_PROG_REC,
CASE WHEN BILS01_DATA_PRES_ISTSOSP<TO_DATE('9999-12-31','YYYY-MM-DD') AND BILS01_CTR_IST_SOSP=0 THEN BILS01_DATA_PRES_ISTSOSP
WHEN BILS01_DATA_PRES_ISTSOSP=TO_DATE('9999-12-31','YYYY-MM-DD') AND BILS01_CTR_IST_SOSP>0 THEN DATA_CONTROVERSIA2
WHEN BILS01_DATA_PRES_ISTSOSP=TO_DATE('9999-12-31','YYYY-MM-DD') AND BILS01_CTR_IST_SOSP=0 THEN TO_DATE('9999-12-31','YYYY-MM-DD')
WHEN BILS01_DATA_PRES_ISTSOSP<
(
CASE WHEN
(
CASE WHEN BILS01_DATA_SPED<to_date('9999-12-31','YYYY-MM-DD') THEN BILS01_DATA_SPED
WHEN BILS01_DATA_SPED=to_date('9999-12-31','YYYY-MM-DD') OR BILS01_DATA_RIC<to_date('9999-12-31','YYYY-MM-DD')THEN BILS01_DATA_RIC
WHEN BILS01_DATA_ACQ<to_date('9999-12-31','YYYY-MM-DD') THEN BILS01_DATA_ACQ ELSE BILS01_DATA_PROT END AS DATA_CONTROVERSIA
)
<TO_DATE('1972-01-01','YYYY-MM-DD') THEN TO_DATE('1972-01-01','YYYY-MM-DD') ELSE DATA_CONTROVERSIA END AS DATA_CONTROVERSIA2
)
THEN BILS01_DATA_PRES_ISTSOSP ELSE DATA_CONTROVERSIA2 END AS A) AS OUT_DATA_RICH_SOSP
FROM zucow.BILS01
--GROUP BY BILS01_GRADO, BILS01_CODICE_COM, BILS01_PROT, BILS01_PROG_OGG_IMP,
-- BILS01_PROG_REC, OUT_DATA_RICH_SOSP

SQL to get whole words till end from the keyword

Consider I have text from the field (notes) as below:
Please check http://example.com
I want a SQL query which fetches the link part only. That is to find keyword http and print till the last.
Output:
http://example.com
Also if the text field doesnt have any link, can we print NA?
CASE WHEN sys like '%Clo%'
THEN RIGHT( i.notes,LEN(i.notes) - CHARINDEX('http',i.notes,1)+1)
ELSE "No Link Available" END AS Cl_Link
For SQL Server you can consider this below logic-
DECLARE #T VARCHAR(MAX) = 'Please check http://example.com'
SELECT RIGHT(#T,LEN(#T) - CHARINDEX('http:',#T,1)+1)
For MySQL-
SET #T = 'Please check http://example.com';
SELECT RIGHT(#T,LENGTH(#T) - POSITION("http:" IN #T)+1)
In case of select query using table, queries will be-
-- SQL Server
SELECT RIGHT(column_name,LEN(column_name) - CHARINDEX('http:',column_name,1)+1) FROM your_table_name
-- MySQL
SELECT RIGHT(column_name,LENGTH(column_name) - POSITION("http:" IN column_name)+1) FROM your_table_name
To apply 'NA' when no link available, please use the below logic-
DECLARE #T VARCHAR(MAX) = 'Please check http://example.com'
SELECT
CASE
WHEN CHARINDEX('http:',#T,1) >= 1 THEN RIGHT(#T,LEN(#T) - CHARINDEX('http:',#T,1)+1)
ELSE 'NA'
END
Below is the query for your reference, executed on mysql:
SELECT substr(columnname,locate('http',columnname)) as link
FROM `tablename` where column=value
For MySQL try this:
select REGEXP_SUBSTR(text_column, 'http\:\/\/([\\w\\.\\S]+)') from mytest

Using variable in Oracle function

I have a variable and want to use in a query inside fuzzy function but it is giving me some syntax error or wrong result considering the var.
ORA-20000: Oracle Text error:
DRG-50901: text query parser syntax error on line 1, column 21 29902.
00000 - "error in executing ODCIIndexStart() routine"
When I replace the my_var variable in the fuzzy function with some static string it works fine but with variable it is giving me this error.
My query is as follows:
DEFINE my_var = 'Bhularam';
SELECT a.EXTERNALID_ENC,
a.EXTERNALID,
a.TELNUMBER,
a.TELAREACODE,
a.DQ_ENGLISH_NAME,
a.DQ_ARABIC_NAME,
a.NAMEFIELD_1,
a.USAGETYPE,
a.MANUAL_UPDATE_FLAG,
a.RULE_UPDATE_FLAG,
a.BUSINESS_UPDATE_FLAG,
a.EXCEL_UPDATE_FLAG
FROM (
SELECT * FROM (
SELECT dqlist.*,
score(1) AS rank
FROM dq_list_hash_full dqlist
WHERE contains(dqlist.dq_english_name
,'definescore(fuzzy(my_var, 1, 6, weight),relevance)',1) > 0
UNION
SELECT
dqlist.*,
score(1) AS rank
FROM
dq_list_hash_full dqlist
WHERE
contains(dqlist.dq_english_name,'!Bhularam',1) > 0
)
ORDER BY
rank DESC
) a
I know it is something really stupid but I am unable to get my head around it probably I am new to oracle. Please help me out.
If using sqlplus, verify what prefix character is used to identify substitution variables. Default is set to '&'.
sqlplus > show define
define "&" (hex 26)
Try using your substitution variable within your query, for example
sqlplus > define my_var='hello world!'
sqlplus > select '&my_var' from dual;
old 1: select '&my_var' from dual
new 1: select 'hello world!' from dual
'HELLOWORLD!'
--------------------------------
hello world!
For your query try (assuming define is set to '&'):
'definescore(fuzzy(&my_var, 1, 6, weight),relevance)',1)

Selecting one out of many strings with concatenation in Redshift

I have to match the following URLs by writing a query in Amazon Redshift:
<some url>/www.abc.com/a/<more url>
<some url>/www.abc.com/b/<more url>
<some url>/www.abc.com/c/<more url>
<some url>/www.abc.com/d/<more url>
Here, obviously the "/www.abc.com/" is constant, but the text after '/' can change. It can take one of the many values that I have a list of (a,b,c,d in this case). How do I match this part that comes immediately after "/www.abc.com/"?
I can think of the following:
select text,
case
when text ilike '%/www.abc.com/' || <what should go here?> || '/%' then 'URLType1'
when <some other condition> then 'URLType2'
end as URLType
from table
I have to maintain the CASE structure.
Any help would be much appreciated.
THe options are:
1) put the list of values into a subquery and then join to this list like this:
with
value_list as (
select 'a' as val union select 'b' union select 'c' union select 'd'
)
select text
from table
join value_list
on text ilike '%/www.abc.com/' || val || '/%'
2) use OR:
select text,
case
when text ilike '%/www.abc.com/a/%'
or text ilike '%/www.abc.com/b/%'
or text ilike '%/www.abc.com/c/%'
or text ilike '%/www.abc.com/d/%'
then 'URLType1'
when <some other condition>
then 'URLType2'
end as URLType
from table
3) Write a Python UDF that takes the url and the list and returns true or false like this:
CREATE OR REPLACE FUNCTION multi_ilike(str varchar(max),arr varchar(max))
RETURNS boolean
STABLE AS $$
if str==None or arr==None:
return None
arr = arr.split(',')
str = str.lower()
for i in arr:
if i.lower() in str:
return True
return False
$$ LANGUAGE plpythonu;
select multi_ilike('<some url>/www.abc.com/a/<more url>','/www.abc.com/a/,/www.abc.com/b/,/www.abc.com/c/,/www.abc.com/d/'); -- returns true
select multi_ilike('<some url>/www.abc.com/F/<more url>','/www.abc.com/a/,/www.abc.com/b/,/www.abc.com/c/,/www.abc.com/d/'); -- returns false

How to match numbers that are present between ] and [?

How do I match numbers that are present between ] and [ (not [ and ])?
EDIT-1
In other words, I want to extract those rows where I have a number between ] and [.
My table looks like this...
ID1 id mycolmn
1 100 [ab-ee]43[ddhj]
2 233 [aa-33]49[kl-00]
3 344 [ss-23][wdsd]
And I should get
43
49
EDIT-1 ends
See example file here. I have a column in MyDatabase and I want to extract those rows where there are two digit numbers between ] and [.
Example [ab-ee]43[ddhj] or [aa-33]49[kl-00]
The following did not work.
SELECT * from myTable where [mycolmn] Like "*\]##\[*"
You can use VBA or SQL.
VBA:
Function GetCode(MyColumn As String) As String
Dim RE As New RegExp
Dim colMatches As MatchCollection
With RE
.Pattern = "\]\d\d\["
.IgnoreCase = True
.Global = False
.Multiline = False
Set colMatches = .Execute(MyColumn)
End With
If colMatches.Count > 0 Then
GetCode = Replace(Replace(colMatches(0).Value, "[", ""), "]", "")
Else
GetCode = ""
End If
End Function
And you would call it like this:
SELECT GetCode([test]) AS MyDigits
FROM test;
If you want a strait SQL solution:
SELECT Mid([test],InStr([test],"]")+1,2) AS MyDigits
FROM test;
This assumes that your numbers come after the first ]. If not, it can be modified with more IIF, INSTR, & MID functions to match your pattern. It would be ugly, but it can work.
Yo dawg I heard you like brackets so I put brackets in your brackets so you can escape your brackets
Select * FROM yourTable WHERE MAtch LIKE "*]##[ [ ]*"
Select Mid([MyColumn],InStr([MyColumn],"]")+1,2) AS MyDigits
FROM yourTable WHERE [MyColumn] LIKE "*]##[ [ ]*"
Please award the check if this answer suits your needs. That's how StackOverflow works.
You can try PATINDEX:
create table TestPatIndex
(
MyData varchar(100)
)
insert into TestPatIndex select '[ab-ee]43[ddhj]'
insert into TestPatIndex select '[ab-ee]XX[ddhj]'
select SUBSTRING(MyData, PATINDEX ('%][0-9][0-9][[]%', MyData ) + 1, 2)
from TestPatIndex
where isnumeric(SUBSTRING(MyData, PATINDEX ('%][0-9][0-9][[]%', MyData ) + 1, 2)) = 1
Here is a link to SQL fiddle.
Something like this should work in MS Access:
SELECT MyData AS Expr1
FROM TestPatIndex
where MyData like '*][0-9][0-9][[]*'