How select an aggregated row in SQL? - sql

I have a table with aggregated columns like this in a SQL Server. The goal is: Show me any row that contains Street A or B.
Name
Adresses
Mike
Street A, Street B, Street C
Smith
Street B
Jimmy
Street C
Declare #street table (col nvarchar (50) )
INSERT INTO #street Values ('Street A'), ('Street B' )
SELECT *
FROM Table
WHERE Adresses like '%' + #street + '%'
SELECT *
FROM Table
WHERE Adresses = ( SELECT * FROM #street )
SELECT *
FROM Table
WHERE STRING_SPLIT(Adresses,',') in ( SELECT * FROM #street )
It does not work. I do not get results. The results should be like this:
Name
Adresses
Mike
Street A, Street B, Street C
Smith
Street B

You should get rid of this bad structure and store the data in a better form in future.
Anyway, following your intention to use STRING_SPLIT for that, this would do:
SELECT name, adresses
FROM yourtable
WHERE EXISTS
(SELECT *
FROM STRING_SPLIT(adresses, ',')
WHERE value IN ('Street A', 'Street B'));
You should read the documentation, that's explained there.
Testing with your sample data succeeds: db<>fiddle

I am sure you can use some "contains" functionality on column adresses. Depends if the column is a varchar/text like column, or a array like column.
However, i would instead try to solve this in a more conseptual level.
In relational databases, this would be referred as a "many to one" relationship.
One adress may have only one Persons related to them, while the Person may have listed many Adresses.
Therefore i would make seperate tables. Then you can easily Search the Adresses table for A and B and find related foreign keys to Persons table.
Otherwise, you can insist on using "contains" functionality, but this might get computationally expensive.

Related

how to filter by field contain another field

I have a table with a field of "content" and a field of a "country".
and I need to check if the country name appears in the text's content.
content:
"La baguette est originaire de France"
"החומוס הטוב ביותר הוא בישראל"
"Michael Phelps earned his final gold medal when the United States
team won the 4×100-meter medley relay."
country:
France
ישראל
United States
using like clause seems to be the right option, but I don't know how to use the values in the country field for this type of check.
Naive approach with dictionary table:
CREATE TABLE country(id INT, name NVARCHAR(100));
INSERT INTO country(id, name) VALUES (1, 'United States'), (2, 'France'), (3, N'ישראל');
SELECT *
FROM mytable m
JOIN country c
ON m.content LIKE '%' + c.name + '%';
Of course it is not bullet-proof solution, because country could be different depending on language and noun case.
EDIT:
If country is present on the same row:
SELECT *,
CASE WHEN m.content LIKE '%' + m.country + '%' THEN 'Present' ELSE 'None' END
FROM mytable m
As you just need to check the data from other table you can just have a subquery or as per your data row by row to do it without subquery like
SELECT Case
when Content Like '%'+country+'%'
then "Yes" else "No" end, content,
country from table ;
or via subquery
SELECT
content,
country from table where content IN
(Select '%'+country+'%' from table )
;
I think you want:
where Content like N'%' + country + N'%'
This would return rows where the country is in the content. You seem to have multiple character sets, so I think nvarchar() is appropriate.
Attached answer using PostgreSQL.
I used the position function but there are similar functions for other databases (instr for Oracle, for example).
select * from $table_name$ a
where position(country in content) > 0;

SQL using where contains to return rows based on the content of another table

I need some help:
I have a table called Countries, which has a column named Town and a column named Country.
Then I have table named Stores, which has several columns (it is a very badly set up table) but the ones that are important are the columns named Address1 and Address2.
I want to return all of the rows in Stores where Address1 and Address2 contains the towns in the Countries table.
I have a feeling this is a simple solution but I just can't see it.
It would help if maybe you could use WHERE CONTAINS but in your parameters search in another table's column?
e.g.
SELECT *
FROM Stores
WHERE CONTAINS (Address1, 'Select Towns from Countries')
but obviously that is not possible, is there a simple solution for this?
You're close
SELECT * FROM Stores s
WHERE EXISTS (
SELECT * FROM Countries
WHERE CONTAINS(s.Address1, Town) OR CONTAINS(s.Address2, Town)
)
This would be my first attempt:
select * from stores s
where
exists
(
select 1 from countries c
where s.Address1 + s.Address2 like '%'+c.Town+'%'
)
Edit: Ooops just saw that you want the 'CONTAINS' clause. Then take Paul's solution

MySQL SELECT query string matching

Normally, when querying a database with SELECT, its common to want to find the records that match a given search string.
For example:
SELECT * FROM customers WHERE name LIKE '%Bob Smith%';
That query should give me all records where 'Bob Smith' appears anywhere in the name field.
What I'd like to do is the opposite.
Instead of finding all the records that have 'Bob Smith' in the name field, I want to find all the records where the name field is in 'Robert Bob Smith III, PhD.', a string argument to the query.
Just turn the LIKE around
SELECT * FROM customers
WHERE 'Robert Bob Smith III, PhD.' LIKE CONCAT('%',name,'%')
You can use regular expressions like this:
SELECT * FROM pet WHERE name REGEXP 'Bob|Smith';
Incorrect:
SELECT * FROM customers WHERE name LIKE '%Bob Smith%';
Instead:
select count(*)
from rearp.customers c
where c.name LIKE '%Bob smith.8%';
select count will just query (totals)
C will link the db.table to the names row you need this to index
LIKE should be obvs
8 will call all references in DB 8 or less (not really needed but i like neatness)

Return multiple values in one column within a main query

I am trying to find Relative information from a table and return those results (along with other unrelated results) in one row as part of a larger query.
I already tried using this example, modified for my data.
How to return multiple values in one column (T-SQL)?
But I cannot get it to work. It will not pull any data (I am sure it is is user[me] error).
If I query the table directly using a TempTable, I can get the results correctly.
DECLARE #res NVARCHAR(100)
SET #res = ''
CREATE TABLE #tempResult ( item nvarchar(100) )
INSERT INTO #tempResult
SELECT Relation AS item
FROM tblNextOfKin
WHERE ID ='xxx' AND Address ='yyy'
ORDER BY Relation
SELECT #res = #res + item + ', ' from #tempResult
SELECT substring(#res,1,len(#res)-1) as Result
DROP TABLE #tempResult
Note the WHERE line above, xxx and yyy would vary based on the input criteria for the function. but since you cannot use TempTables in a function... I am stuck.
The relevant fields in the table I am trying to query are as follows.
tblNextOfKin
ID - varchar(12)
Name - varchar(60)
Relation - varchar(30)
Address - varchar(100)
I hope this makes enough sense... I saw on another post an expression that fits.
My SQL-fu is not so good.
Once I get a working function, I will place it into the main query for the SSIS package I am working on which is pulling data from many other tables.
I can provide more details if needed, but the site said to keep it simple, and I tried to do so.
Thanks !!!
Follow-up (because when I added a comment to the reponse below, I could not edit formatting)
I need to be able to get results from different columns.
ID Name Relation Address
1, Mike, SON, 100 Main St.
1, Sara, DAU, 100 Main St.
2, Tim , SON, 123 South St.
Both the first two people live at the same address, so if I query for ID='1' and Address='100 Main St.' I need the results to look something like...
"DAU, SON"
Mysql has GROUP_CONCAT
SELECT GROUP_CONCAT(Relation ORDER BY Relation SEPARATOR ', ') AS item
FROM tblNextOfKin
WHERE ID ='xxx' AND Address ='yyy'
You can do it for the whole table with
SELECT ID, Address, GROUP_CONCAT(Relation ORDER BY Relation SEPARATOR ', ') AS item
FROM tblNextOfKin
GROUP BY ID, Address
(assuming ID is not unique)
note: this is usually bad practice as an intermediate step, this is acceptable only as final formatting for presentation (otherwise you will end up ungrouping it which will be pain)
I think you need something like this (SQL Server):
SELECT stuff((select ',' +Relation
FROM tblNextOfKin a
WHERE ID ='xxx' AND Address ='yyy'
ORDER BY Relation
FOR XML path('')),1,1,'') AS res;

Get words from sentence - SQL

Suppose I have a description column that contains
Column Description
------------------
I live in USA
I work as engineer
I have an other table containing the list of countries, since USA (country name) is mentioned in first row, I need that row.
In second case there is no country name so I don't need that column.
Can you please clarify
You may want to try something like the following:
SELECT cd.*
FROM column_description cd
JOIN countries c ON (INSTR(cd.description, c.country_name) > 1);
If you are using SQL Server, you should be able to use the CHARINDEX() function instead of INSTR(), which is available for MySQL and Oracle. You can also use LIKE as other answers have suggested.
Test case:
CREATE TABLE column_description (description varchar(100));
CREATE TABLE countries (country_name varchar(100));
INSERT INTO column_description VALUES ('I live in USA');
INSERT INTO column_description VALUES ('I work as engineer');
INSERT INTO countries VALUES ('USA');
Result:
+---------------+
| description |
+---------------+
| I live in USA |
+---------------+
1 row in set (0.01 sec)
This is a really bad idea, to join on arbitrary text like this. It will be very slow and may not even work.. give it a shot:
select t1.description, c.*
from myTable t1
left join countries c on t1.description like CONCAT('%',c.countryCode,'%')
Its not entierly clear from your post but I think you are asking to return all the rows in the table that contain the descriptions which contain a certain country name? If thats the case you can just use the sql LIKE operator like the following.
select
column_description
from
description_table
where
column_description like %(select distinct country_name from country)%
If not I think your only other choice is Dans post.
Enjoy !
All the suggestions so far seem to match partial words e.g. 'I AM USAIN BOLT' would match the country 'USA'. The question implies that matching should be done on whole words.
If the text was consisted entirely of alphanumeric characters and each word was separated by a space character, you could use something like this
Descriptions AS D1
LEFT OUTER JOIN Countries AS C1
ON ' ' + D1.description + ' '
LIKE '%' + ' ' + country_name + ' ' + '%'
However, 'sentence' implies punctuation e.g. the above would fail to match 'I work in USA, Goa and Iran.' You need to delimit words before you can start matching them. Happily, there are already solutions to this problem e.g. full text search in SQL Server and the like. Why reinvent the wheel?
Another problem is that a single country can go by many names e.g. my country can legitimately be referred to as 'Britain', 'UK', 'GB' (according to my stackoverflow profile), 'England' (if you ask my kids) and 'The United Kingdom of Great Britain and Northern Ireland' (the latter is what is says on my passport and no it won't fit in your NVARCHAR(50) column ;) to name but a few.