Check address voor 2 properties and display in same row - sql

From the Persons table I would like to get the following output:
Number FirstName AddressAvenue AddressFloor
----------------------------------------------
1 David Long Avenue 5th Floor
2 Bob Short Avenue NULL
3 Peter Middle Avenue 1st Floor
(Apparently, Bob his address does not contain a Floor number).
I thought I would get this by running the following query:
select
p.Number
p.FirstName
, case when (p.Street like '%Avenue%') then p.Street end as AddressAvenue
, case when (p.Street like '%Floor%') then p.Street end as AddressFloor
from
#persons
;
However, the output is as follows:
Number FirstName AddressAvenue AddressFloor
----------------------------------------------
1 David Long Avenue NULL
2 Bob Short Avenue NULL
3 Peter Middle Avenue NULL
1 David NULL 5th Floor
3 Peter NULL 1st Floor
Question How can I get both Address and Floor on the same line?
Any help is greatly appreciated!

Try this bad boy
CREATE TABLE #persons
(
Number INT
,FirstName VARCHAR(10)
,Street VARCHAR(50)
)
INSERT #persons
VALUES
(1, 'David', 'Long Avenue'),
(2, 'Bob', 'Short Avenue'),
(3, 'Peter', 'Middle Avenue'),
(1, 'David', '5th Floor'),
(3, 'Peter', '1st Floor')
--This is the code you really want, I just needed the rest to test it and make sure it worked
SELECT DISTINCT
z.Number
,z.FirstName
,(SELECT p.Street FROM #persons p where p.Street LIKE '%Avenue%' AND p.Number = z.Number)
,(SELECT p.Street FROM #persons p where p.Street LIKE '%Floor%' AND p.Number = z.Number)
FROM #persons z
DROP TABLE #persons
Results in the following:

Related

How can I find a string separated by a space in SQL

I am trying to find a way where I can skim out records of customers where 'First Name' and 'Middle Name' has been entered in the first_name column in the customer detail table. For examples
first_name, Last_name, mobile_no
Mary Jane Smith 0400000000
Shane Angus John 0400000000
Rudy Gill 0401111111
Rachel Rose
from the above examples I only want to find records
Mary Jane Smith 0400000000
Shane Angus John 0400000000
You can use like:
select t.*
from t
where first_name like '% %';
Note: This just checks for a space. It does not guarantee that one of the names is a middle name.
here's another solution for you if you want to get more complex and account for the middle name.
create table test (first_name nvarchar(50), middle_name nvarchar(50), last_name nvarchar(75), mobile_no nvarchar(10))
insert test
select 'mary jane', null, 'smith', '0400000000'
union all
select 'shane angus', null, 'john', '0400000000'
union all
select 'rudy', 'jacob', 'gill', '0401111111'
union all
select 'rachel', 'liza', 'rose', '0400000000'
select *
from test
where middle_name is null and charindex(char(32),first_name) > 0
this won't help you though if the first name is double-worded like Bobby Jo hence the middle name check.

Why is no data being returned

I am trying to find majors that end with S, but no data is being returned
create table Student
(sid char(10) primary key,
sname varchar(20) not null,
gpa float,
major char(10),
dob DATE);
insert into Student values('111', 'Joe', 3.5 , 'MIS', '01-AUG-2000');
insert into Student values('222', 'Jack', 3.4 , 'MIS', '12-JAN-1999');
insert into Student values('333', 'Jill', 3.2 , 'CS', '15-MAY-1998');
insert into Student values('444', 'Mary', 3.7 , 'CS', '17-DEC-2001');
insert into Student values('555', 'Peter', 3.8 , 'CS', '19-MAR-1999');
insert into Student values('666', 'Pat', 3.9, 'Math', '31-MAY-2000');
insert into Student values('777', 'Tracy', 4.0, 'Math', '18-JUL-1997');
SELECT * FROM STUDENT
WHERE MAJOR LIKE '%S'
This doesn't work on livesql (oracle (PL-SQL) based but works on T-SQL).
This is the error message: 'No data found'
Your CHAR(10) will always contain 10 characters so it is going to be padded with space characters. Change to VARCHAR2(10) and it will work. I'm assuming Oracle since you didn't specify which database. But VARCHAR(10) should work with T-SQL.
If you can't (or won't) modify datatype to varchar2 (not varchar as Stilgar suggested), then trimming the column might help:
SQL> select * from student
2 where trim(major) like '%S';
SID SNAME GPA MAJOR DOB
---------- -------------------- ---------- ---------- --------
111 Joe 3,5 MIS 01.08.00
222 Jack 3,4 MIS 12.01.99
333 Jill 3,2 CS 15.05.98
444 Mary 3,7 CS 17.12.01
555 Peter 3,8 CS 19.03.99

Matching First and Last Name on two different tables

I am trying to match the first name varchar (50) and last name varchar(50) from table A to the first name varchar(50) and last name varchar(50) on table B. The issue is that both table contain a lot of shortened first names like the name Andrew in table A and there might be a matching record with the last name but the first name is Andy so it comes up as not a match. Is there anyway to get around this in SQL. The shortened names is a vice verse problem meaning that both Table A and Table B have some shortened names.
Here are some more examples:
This is my current code.
Select *
FROM TableA p
JOIN TableB e ON e.CompanyNumber = 1 and e.LastName like '%' + rtrim(ltrim(p.lastname)) + '%'
and e.FirstName like '%' + ltrim(rtrim(p.firstname)) + '%'
NOTE: This is the only way to match the tables together.
Create a third table that associates Long-form and short-form names.
For examle:
Long Form Short Form
Andrew Andy
Andrew Drew
David Dave
William Will
William Bill
William Billy
William Willy
Provided you use a 3rd Table to hold you Long/Short Names as so.
CREATE TABLE TableNames
([Id] int, [OfficialName] varchar(7), [Alias] varchar(7))
;
INSERT INTO TableNames
([Id], [OfficialName], [Alias])
VALUES
(1, 'Andrew', 'Andy'),
(2, 'Andrew', 'Andrew'),
(3, 'William', 'Bill'),
(4, 'William', 'William'),
(5, 'David', 'Dave'),
(6, 'David', 'David')
The following query should give you what you are looking for.
SELECT *
FROM (
SELECT TableA.Id AS T1_Id
,CompanyId AS T1_CompanyId
,FirstName AS T1_FirstName
,LastName AS T1_LastName
,TableNames.OfficialName AS OfficialName
FROM tableA
INNER JOIN tableNames ON TableA.FirstName = TableNames.Alias
) T1
,(
SELECT tableB.Id AS T2_Id
,CompanyId AS T2_CompanyId
,FirstName AS T2_FirstName
,LastName AS T2_LastName
,TableNames.OfficialName AS OfficialName
FROM tableB
INNER JOIN tableNames ON TableB.FirstName = TableNames.Alias
) T2
WHERE T1.T1_CompanyId = T2.T2_CompanyId
AND T1.OfficialName = T2.OfficialName
AND T1.T1_LastName = T2.T2_LastName
I set up my solution sqlfiddle at http://sqlfiddle.com/#!3/64514/2
I hope this helps.
Select *
<br>FROM TableA pJOIN TableB e
<br>ON e.CompanyNumber = 1
<br>and e.LastName like '%' + rtrim(ltrim(p.lastname)) + '%'
<br>OR
<br>e.FirstName like '%' + ltrim(rtrim(p.firstname)) + '%'
Now this depends how you determine it is match,
example:
TableA:
--------
Rownum FristName LastName
1 Andy Smith
2 Andy Mathew
TableB:
--------
Rownum FristName LastName
1 Logan Andy
2 Mathew Andy
Now will you consider first record from both the tables as a match
What about the second record in both the tables?
Basing on this we can even change the query

Combining more than one piece of data in a cell. sql

This is for a Homework assignment, but I want to go a step farther.
Let me show my Tables then I'll ask my question.
Table -- Students
StudentID PK, LastName, FirstName,
Table -- Courses
CourseID PK, CourseName
Table -- Registrations
StudentID FK, CourseID FK
The question is How can I add more than one CourseName in that specific cell? For Example I have one student who is taking 3 classes, can I show all 3 CourseNames for that particular student in the same cell in the same row?
Example.......
123456, Smith, John, English, Math, Science
Sorry if this seems simplistic but I just can't find what I'm looking for after searching.
You don't put them into 1 cell.
It will be 3 rows. An example will make this a bit more clear:
John Smith: ID 1025
Math ID 2500
English ID 2585
Violin ID 3250
In your database you will get the following rows:
StudentID CourseID
1025 2500
1025 2585
1025 3250
Well in the spirit of Christmas you can always imagine it's a turkey and STUFF it..
DECLARE #Students TABLE(StudentID INT, LastName VARCHAR(50), FirstName VARCHAR(50))
DECLARE #Courses TABLE(CourseID INT, CourseName VARCHAR(50))
DECLARE #Registrations TABLE(StudentID INT, CourseID INT)
INSERT INTO #Students VALUES
(123456, 'John', 'Smith'),(123457, 'Adrian', 'Sullivan'),(123458, 'Dude', 'Guy')
INSERT INTO #Courses VALUES
(1,'English'),(2,'Math'),(3,'Science')
INSERT INTO #Registrations VALUES
(123456,1),(123456,2),(123456,3),(123457,1),(123457,2),(123458,3)
DECLARE #STID INT
SELECT *, STUFF((SELECT ','+C2.CourseName
FROM #Registrations R2
INNER JOIN #Courses C2 ON C2.CourseID = R2.CourseID
WHERE R2.StudentID = S.StudentID
FOR XML PATH(''), TYPE).value('.', 'nvarchar(max)'), 1, 1, '') [AllText]
FROM #Students S
For more reading on STUFF

Distinct over one column with value comparing on another column ICriteria NHibernate

I have table and object called Person. I have problem to create a distinct (over column "lastname") criteria. I want to get only the oldest Person with distinct lastnames.
For example i have (properties: firstname, lastname, age):
John Smith, 52
Jessica Smith, 45
Ann Pit, 21
Brad Pit, 30
Can anybody help me to create criteria which result i get Person object with John Smith and Brad Pit?
Probably the best approach here is to use EXISTS to filter the result set, first a SQL example to get the logic correct:
DECLARE #Person TABLE (
Id INT,
Firstname VARCHAR(20),
Lastname VARCHAR(20),
Age INT
)
INSERT INTO #Person VALUES (1, 'Brad', 'Pitt', 42)
INSERT INTO #Person VALUES (2, 'Angelina', 'Pitt', 45)
INSERT INTO #Person VALUES (3, 'John', 'Smith', 50)
INSERT INTO #Person VALUES (4, 'Jane', 'Smith', 55)
SELECT P.* FROM #Person P
WHERE EXISTS(
SELECT SUB.LastName, MAX(SUB.Age) as Age FROM #Person SUB
GROUP BY SUB.LastName
HAVING SUB.LastName = P.LastName AND MAX(SUB.Age) = P.Age)
This yields the following results which is as expected:
Id Firstname Lastname Age
-------------------------------
2 Angelina Pitt 45
4 Jane Smith 55
Now to convert to nHibernate, this effectively builds the same query as above:
var subQuery = DetachedCriteria.For<Person>("SUB")
.SetProjection(Projections.ProjectionList()
.Add(Projections.GroupProperty("LastName"), "Lastname")
.Add(Projections.Max("Age"), "Age"))
.Add(Restrictions.EqProperty(Projections.Max("Age"), "P.Age")
.Add(Restrictions.EqProperty("LastName", "P.LastName"));
return session.CreateCriteria<Person>("P")
.Add(Subqueries.Exists(subQuery))
.List<Person>();