Compare string data between two tables - sql

i have two tables TABLE 1 with columns
ID Text email ID
============================
1 This is Test 123#g.com
2 Make my day 1234#g.com
TABLE 2 with one column
words(column)
=============
Test
trip
day
now wat i want to do is compare the text ( each and every word) from Table 1 with each row ow word in TABLE 2, if found then the id should be logged on a different table.
example: if from TABLE1 Test is the word which is the row value in the TABLE 2 word column. so it should log ID =1 in a different table.
also once the word is found it shouldn't go for further iteration.

try this:
select *
from TABLE1
join
TABLE2
on ' '+Text+' ' like '% '+words+' %'
SQL fiddle demo

This works
SELECT t1.*,t2.words
FROM Table1 t1
JOIN Table2 t2
ON PATINDEX('%' + t2.words + '%',t1.text)>0
Output
ID Text email_ID words
1 This is Test 123#g.com Test
2 Make my day 1234#g.com day

You can to use CHARINDEX function:
select *
from TABLE1 t1
where exists
(
select 1
from TABLE2 t2
where CHARINDEX(t2.words,t1.text)>0
)
Link to documentation.

Related

SQL Server : select column with 3 matching characters

I am selecting the records from 2 tables in which the 1st table column named DESC (first 3 characters) should match with the project column of the 2nd table.
I want to get the last 2 characters from Table 1 column DESC to be added in my output, but the last 2 characters are not present in Table 2 column project.
select SUBSTRING(a.[DESC], 1, 3)
from Table1 a
join Table2 b on SUBSTRING(a.[DESC], 1, 3) = b.project
Input: 1st Table DESC Column: Value: '2AB F YY'
2nd Table Project Column: Value: '2AB'
Expected Output: Return all the records of value 2AB
Column result:
'2AB YY'
Wrong output: all the records of value starting other then 2AB
One option is as follows
with data
as (
select SUBSTRING(a.[DESC],1,3) as first_3_characters,
,REVERSE(SUBSTRING(REVERSE(a.[DESC]),1,2)) as last_2_char_tab1
,REVERSE(SUBSTRING(REVERSE(b.project),1,2)) as last_2_char_tab2 characters_tab2
from Table1 a
join Table2 b
on SUBSTRING(a.[DESC],1,3) = b.project
)
select *,CONCAT(first_3_characters,last_2_characters)
from data
where last_2_char_tab1 <> last_2_char_tab2
Since you don't seem to need data from Table2, an EXISTS could be used for this.
And RIGHT can be used to get the last N characters of a string.
SELECT
CONCAT(LEFT([DESC], 3),' ', RIGHT([DESC], 2))
FROM Table1 t1
WHERE EXISTS
(
SELECT 1
FROM Table2 t2
WHERE t2.project = LEFT(t1.[DESC], 3)
)
ORDER BY 1;

Sql Query regarding Join

I have two tables as follows:
Table 1:
Name | Specialisation
Table2:
Name | Slot | Date
I take user input of Name, Slot and Date. I want to display the records of Table1 for that Name such that there exists no record corresponding to the entered (Name, Slot, Date) in Table 2. What will be the SQL query for it?
Thanks in advance.
Supposing the input values were input_name, input_slot, and input_data, and the input_date was a suitable date format, one way to do it would be:
select name, specialisation from table1
where (name = input_name)
and (select name from table2
where (table2.name = input_name) and
(table2.slot = input_slot) and
(table2.date = input_date)) is NULL
Or something like that... :)
You can use a not in
select name
from table1
where name not in (
select name from table2
)
or not exists
select name
from table1
where name not exists (
select name from table2
where table2.name = table1.name
)

Combine three columns from different tables into one row

I am new to sql and are trying to combine a column value from three different tables and combine to one row in DB2 Warehouse on Cloud. Each table consists of only one row and unique column name. So what I want to is just join these three to one row their original column names.
Each table is built from a statement that looks like this:
SELECT SUM(FUEL_TEMP.FUEL_MLAD_VALUE) AS FUEL
FROM
(SELECT ML_ANOMALY_DETECTION.MLAD_METRIC AS MLAD_METRIC, ML_ANOMALY_DETECTION.MLAD_VALUE AS FUEL_MLAD_VALUE, ML_ANOMALY_DETECTION.TAG_NAME AS TAG_NAME, ML_ANOMALY_DETECTION.DATETIME AS DATETIME, DATA_CONFIG.SYSTEM_NAME AS SYSTEM_NAME
FROM ML_ANOMALY_DETECTION
INNER JOIN DATA_CONFIG ON
(ML_ANOMALY_DETECTION.TAG_NAME =DATA_CONFIG.TAG_NAME AND
DATA_CONFIG.SYSTEM_NAME = 'FUEL')
WHERE ML_ANOMALY_DETECTION.MLAD_METRIC = 'IFOREST_SCORE'
AND ML_ANOMALY_DETECTION.DATETIME >= (CURRENT DATE - 9 DAYS)
ORDER BY DATETIME DESC)
AS FUEL_TEMP
I have tried JOIN, INNER JOIN, UNION/UNION ALL, but can't get it to work as it should. How can I do this?
Use a cross-join like this:
create table table1 (field1 char(10));
create table table2 (field2 char(10));
create table table3 (field3 char(10));
insert into table1 values('value1');
insert into table2 values('value2');
insert into table3 values('value3');
select *
from table1
cross join table2
cross join table3;
Result:
field1 field2 field3
---------- ---------- ----------
value1 value2 value3
A cross join joins all the rows on the left with all the rows on the right. You will end up with a product of rows (table1 rows x table2 rows x table3 rows). Since each table only has one row, you will get (1 x 1 x 1) = 1 row.
Using UNION should solve your problem. Something like this:
SELECT
WarehouseDB1.WarehouseID AS TheID,
'A' AS TheSystem,
WarehouseDB1.TheValue AS TheValue
FROM WarehouseDB1
UNION
SELECT
WarehouseDB2.WarehouseID AS TheID,
'B' AS TheSystem,
WarehouseDB2.TheValue AS TheValue
FROM WarehouseDB2
UNION
WarehouseDB3.WarehouseID AS TheID,
'C' AS TheSystem,
WarehouseDB3.TheValue AS TheValue
FROM WarehouseDB3
Ill adapt the code with your table names and rows if you tell me what they are. This kind of query would return something like the following:
TheID TheSystem TheValue
1 A 10
2 A 20
3 B 30
4 C 40
5 C 50
As long as your column names match in each query, you should get the desired results.

SQL Server query with intersect except or union relational Algebra

I am trying to solve a problem. It seems that of a brain teaser if you ask me.
Given two tables, return only values from the first table when there is a match for EVERY record in a second table. So a record in table 1 must have a match to every record in table 2. If table 2 has fewer than every row I want to exclude it from the final result.
This must be done without using count, having, group by. I must solve it with union, intersect, except, exists.
I am using SQL Server BTW.
CREATE TABLE table1 (id int, lid int)
INSERT INTO table1 VALUES (1, 1),(1, 2),(1,3),(1,4),(2,1),(3,3),(4,4)
CREATE TABLE table2 (lid int)
INSERT INTO table2 VALUES (1),(2),(3),(4)
Table 1:
id lid
--------
1 1
1 2
1 3
1 4
2 1
3 3
4 4
Table2:
lid
-----
1
2
3
4
This method here is "not the way I am supposed to solve it". Frustrating because this solution is so simple and does exactly what it should do. I can't use count, group by, and having.
SELECT id
FROM dbo.table1, dbo.table2
WHERE table1.lid = table2.lid
GROUP BY id
HAVING COUNT(*) = (SELECT COUNT(*) FROM dbo.table2)
So basically I need to find a way to exclude the results from the first table when there is not a full set of matches in table 2. In this example the only value in table 1 with a match to every record in table 2 is 1. 2,3,4 would need to be excluded.
What you're looking for has a name. It's called relational division. It has no equivalent in SQL, although it can be emulated in a variety of ways. Joe Celko has written one of the most complete blog posts about the topic.
Since you must use some of the more basic relational operators in SQL, this could be one solution for you:
SELECT DISTINCT id
FROM table1 t1a
WHERE NOT EXISTS (
SELECT *
FROM table2
WHERE NOT EXISTS (
SELECT *
FROM table1 t1b
WHERE t1a.id = t1b.id
AND t2.lid = t1b.lid
)
)
It reads in English, informally:
Get me all the elements in table1 for which there is no element in table2, which doesn't match such an element from table1
Or also:
Get me the elements from table1, which match all the elements in table2
That's one of the solutions:
select distinct id from table1 AS T1
where not exists(
select lid from table2
except
select lid from table1 where id = T1.id
)

How to validate a column of a table with combination of another columns of another table?

I have to check for the validation of a field present in one table with the fields present in another table.
I have a table with a Check_Field present in the (Main table) and this Check_Field has to be validated as a combination of two other fields present in another table(Table 2).
Main Table
Check_Field
-------------
Field_1%Field_2%
Table 2
Field_1 Field_2
----------------------
ABC XYZ
In the (Main table) I have to check for the field(Check_Field) which contains value of Field_1 from Table 2 followed by a set of predefined characters which is again followed by value of Field_2 from Table 2 and another set of predefined characters.
Something like:
SELECT * FROM MAIN_TABLE M
WHERE EXISTS (
SELECT 1
FROM TABLE2 C
WHERE M.CHECK_FIELD LIKE C.FIELD1¦¦'%'¦¦C.FIELD2¦¦'%'
)
If you have to verify the string with specific additional characters, you can remove the LIKE and insert your characters in the query.
If for example you need to check for patterns like "(field1)XX(field2)ZZ" the query will be:
SELECT * FROM MAIN_TABLE M
WHERE EXISTS (
SELECT 1
FROM TABLE2 C
WHERE M.CHECK_FIELD = C.FIELD1¦¦'XX'¦¦C.FIELD2¦¦'ZZ'
)
You can do this.
Type:
select *
from main_table
where check_field in (
select field_1 from table2
)
This would return value if present in table 2.