How to join 2 tables with alias and condition - sql

Table1: Contractors
Contractor_No; -- PK
Contractor;
Table2: Contracts
Contract_No; -- PK
ProjDesc;
Contractor_No; -- FK
How to retrieve data by joining these 2 table with Contractor (from Table1), Contract_No, ProjDesc from (Table2)?
My SQL statment:
select a.Contractor, b.ProjDesc
from Contractors a, Contracts b
join Contractor a on a.Contractor_No = b.Contractor_No and b.Contract_No='1234';

You have some syntax errors:
SELECT a.Contractor
, b.ProjDesc
FROM Contractors a
JOIN Contracts b ON a.Contractor_No = b.Contractor_No
AND b.Contract_No = '1234'

select a.Contractor,
b.ProjDesc
from Constractors a
inner join contracts b on
a.contractor_no = b.contractor_no
where b.contract_no = '1234'

Related

SQL for 2 tables

I have these 2 tables:
Table A
Country State
-----------------
US OH
US FL
US WA
Table B
State LastVisitDate City
----------------------------------
OH 15/10/2019 Bedford
FL 10/12/2019 Bell
WA 20/09/2019 Perth
Table A can be linked with table B by field "State".
What would be the query to get the latest (last visit date) in country=US, doesn't matter which state, e.g.:
US,10-12-2019,FL,Bell
I tried inner join but couldn't make it work.
Always try to explain your question with sample data and query you tried for.
Here is query with some sample data:
CREATE TABLE A
(
COUNTRY VARCHAR(10),
State VARCHAR(10)
);
INSERT INTO A VALUES('US','OH'),
('US','FL'),
('AU','WA');
CREATE TABLE B
(
State VARCHAR(10),
LastVisitDate DATE,
City VARCHAR(20)
);
INSERT INTO B VALUES
('OH','2019-10-15','Bedford'),
('FL','2019-12-10','Bell'),
('WA','2019-09-20','Perth');
Expected Result:
US,10-12-2019,FL,Bell
Query:
SELECT a.COUNTRY,b.LastVisitDate,b.State,b.City
FROM A
INNER JOIN B ON a.State = b.State
WHERE a.COUNTRY = 'US'
ORDER BY b.LastVisitDate DESC
Limit 1;
SQL Fiddle
Before you try below code you must be reformat last visited date table structure like YYYY/MM/DD in SQL Table and you must replace actual tables name and columns name in below query.
SELECT MAX(table_b.last_visited_date) AS last_visited_date
FROM table_a
INNER JOIN table_b
ON table_a.state = table_b.state WHERE table_a.country = 'US' Limit 1;
Try this below script-
Note: As Tanmay said, you need to reformat your date values to get the correct output.
DEMO HERE
SELECT N.country,
N.mx_date LastVisitDate,
B.City,
B.State
FROM
(
SELECT Country,MAX(LastVisitDate) mx_date
FROM Table_A A
INNER JOIN Table_B B ON A.State = B.State
GROUP BY Country
)N
INNER JOIN Table_A A ON A.Country = N.Country
INNER JOIN Table_B B ON A.State = B.State
WHERE N.mx_date = B.LastVisitDate
SELECT top 1(country,
last_visit_date)
FROM A
JOIN B ON A.State = B.State
WHERE A.Country ="Country Name"
ORDER BY B.Last_visit_Date DESC

SQL Multiple Joins Query

Here I have two tables committee_colleges and colleges.
Structure of tables is something like this
committee_colleges
committeeCollegeId collegeId committeeMemberId
1 2 1
2 2 2
3 3 2
I am storing committeeMemberId from committeeMember table.And one college can have multiple committee Members.How can I wite a query to display only the colleges assigned to specific committee Member.
For Example,if committeeMember by id=2 has logged in I want to display colleges by id=2,3.
In college table I have like this,
collegeId typeName
1 AICTE
2 NCTE
3 NTCS
This is Committee Member table
committeeMemberId name
1 xyz
2 abc
Now I am writing something like this,but i know its wrong because I dont know how to take it from College table since I am displaying College details.
SELECT cc.committeeCollegeId as committeeCollegeId,
c.collegeId as collegeId,
cc.committeeMemberId as committeeMemberId
FROM committee_college as cc
left outer join College as c
on cc.collegeId = c.collegeId
where cc.committeeMemberId=:committeeMemberId
order by cc.committeeCollegeId asc
Can anyone tell how to display colleges based on its assignment to particular committeeMember?
You were close, you need INNER JOIN instead of LEFT JOIN:
SELECT DISTINCT C.typeName --<<== put here all the columns that you want in output
FROM committee_colleges CC
INNER JOIN college C
ON C.collegeId = CC.collegeId
WHERE CC.committeeMemberId = 2 --<<== your input parameter
EDIT: added DISTINCT
Hope it helps.
You can use below sql statement for the same
DECLARE #committeeMemberId INT = 2 -- Id of Committee member
;WITH CTE_MemberCommittee AS
(
SELECT CollegeId
FROM committee_colleges
WHERE committeeMemberId = #committeeMemberId
)
SELECT collegeId, typeName
FROM college
WHERE collegeId IN (SELECT CollegeId FROM CTE_MemberCommittee)
You can use simple inner join for that,
If you want collegename based on memberId use following query,
select a.collegeid,a.typeName from
college a, committee_colleges b, committe_member c
where a.collegeid = b.collegeid and
b.committeememberid = c.committeeMemberId
and c.committeeMemberId = '2'
If you want collegename based on committemember name then use following query,
select a.collegeid,a.typeName from
college a, committee_colleges b, committe_member c
where a.collegeid = b.collegeid and
b.committeememberid = c.committeeMemberId
and c.Name = 'xyz'
Hope it will help.
try this:
DECLARE #LoginCommitteeMemberId INT=2
SELECT t2.Name AS MemberName,
t3.TypeName AS CollageName
FROM committee_college t1
INNER JOIN Committee_Member t2
ON t1.committeeMemberId = t2.committeeMemberId
INNER JOIN College as t3
ON t1.collegeId = t3.collegeId
WHERE t1.committeeMemberId = #LoginCommitteeMemberId

Lookup value in second table

I have two tables.
Table Data
ID Item Kvartal
1 Payment 1
2 Salary 2
Table Kvartal
ID Kvartal_text Kvartal_nummer
1 Q1 1
2 Q2 2
I like to map Kvartal in table Data to Kvartal_text in table Kvartal by matching Kvartal in table Data with ID in table Kvartal. To get a result like Payment Q1; Salary Q2.
I have tried
SELECT * FROM Data
WHERE Data.Kvartal IN (SELECT Kvartal.Kvartal_text
FROM Kvartal
WHERE Kvartal.Kvartal_nummer = Data.Kvartal);
Simply JOIN the two tables and select the fields you want:
SELECT d.Item, k.Kvartal_text
FROM Data d
JOIN Kvartal k
ON k.ID = d.Kvartal
You can use MySQL Join operations for such tasks.
SELECT d.ID, d.Item, d.Kvartal, k.Kvartal_text FROM `Data` d
LEFT JOIN(
SELECT Kvartal_text, Kvartal_nummer FROM `Kvartal`
) AS k
ON k.Kvartal_nummer = d.Kvartal

Selecting from table with categories of people

I created a database in ms sql , in the database I have three category of persons namely staff, customers, suppliers whom I stored in different tables create serial unique id for each.
Now these persons id are stored under person_id and a column names person type which stores whether its a staff, custimer or supplier in the transaction table, The problem lies in selecting the records from the transaction table like this pseudo code
Select t.*,s.na as staff,sp.name as supplier, c.name as customer
From Trans t
left join Staff s on s.id = t.pid
left join Suppliers sp on sp.id = t.pid
left join Customers c on c.id = t.pid
This returns one row, instead of at least 3 or more, How do I solve this problem
My trans table
person_id Person_type Trans_id
1 staff 1
1 customer 2
2 customer 3
3 suppler 4
1 staff 5
Expected output
person_name Trans_id
james 1
mark 2
dan 3
jude 4
james 5
Staff, Customers, and suppliers are stored in their different tables
That's what the Join does, combine data from multiple tables into one result row. If you want to "keep the rows", not combine them, you can use UNION
(
Select t.* From Trans t
left join Staff s on s.id = t.pid
)
UNION
(
Select t.* From Trans t
left join Suppliers sp on sp.id = t.pid
)
UNION
(
Select t.* From Trans t
left join Customers c on c.id = t.pid
)
This will get you the multiple rows you want BUT still not sure you have defined it right. I see you are only taking columns from Trans, so you're not getting any data from the other tables. And you're doing left outer joins so the other tables won't affect the selection. So I think it's just that same as selecting from just Trans.
If what you want is data from Trans where there is corresponding entry in the other tables, then do the UNION, but also change the outer joins to inner.

Oracle Statement does not count correctly

I've got a SQL-statement with a - for me not explainable - strange behaviour.
Perhaps you could find what's wrong:
When I use the statement
select count(*) from department
I got 2755 results
Using the following statement
select
building1.street, building1.streetno, building1.plz, building1.city, dept1.buildingid
from
department dept1
left join
supporter sup
on
dept.supporterid = sup.id
left join
building building1
on
sup.buildingid = building1.ibuildingid
where
dept.usepostaladresssupporter = 1
union all
select
building2.street, building2.streetno, building2.plz, building2.city, dept2.buildingid
from
building building2
right join
tueks_department dept2
on
dept2.buildingid = building2.ibuildingid
where
dept2.usepostaladresssupporter = 0
I got 2755 results too.
But when I want to combine the two statements with a left join:
select count(*) from department
left join
(
select
building1.street, building1.streetno, building1.plz, building1.city, dept1.buildingid
from
department dept1
left join
supporter sup
on
dept.supporterid = sup.id
left join
building building1
on
sup.buildingid = building1.ibuildingid
where
dept.usepostaladresssupporter = 1
union all
select
building2.street, building2.streetno, building2.plz, building2.city, dept2.buildingid
from
building building2
right join
tueks_department dept2
on
dept2.buildingid = building2.ibuildingid
where
dept2.usepostaladresssupporter = 0
) postadress
on
department.buildingid = postadress.buildingid;
I got 3648513 results.
My expectation was, that I get only 2755 results.
Where's the mistake?
Thanks for help!
I assume that buildingid is not unique (for my reasoning to hold true, it can't be unique)
Imagine following simple tables
TableA
create TableA (name VARCHAR(32));
insert into TableA values ('Lieven');
insert into TableA values ('Lieven');
TableB
create TableB (name VARCHAR(32));
insert into TableB values ('Lieven');
insert into TableB values ('Lieven');
insert into TableB values ('AnyOtherValue');
Select statement
select * from TableA a left outer join TableB b on a.name = b.name
As each record of TableA is matched with each record of TableB where the name is equal, this will result in 4 records (the AnyOtherValue is dissmissed as it doesn't match)
The first record of TableA is returned with two of three records of `TableB'
The second record of TableA is returned with two of three records of `TableB'
The query
select
building1.street, building1.streetno, building1.plz, building1.city, dept1.buildingid
from
department dept1
left join
supporter sup
on
dept.supporterid = sup.id
left join
building building1
on
sup.buildingid = building1.ibuildingid
where
dept.usepostaladresssupporter = 1
union all
select
building2.street, building2.streetno, building2.plz, building2.city, dept2.buildingid
from
building building2
right join
tueks_department dept2
on
dept2.buildingid = building2.ibuildingid
where
dept2.usepostaladresssupporter = 0
will return one row per department that has usepostaladresssupporter as either 0 or 1 (note that records with other values will not be included, this may or may not be a problem depending on the constrainst of this column).
The unique key of this query results is probably something like departmentid (you will need to include that column in your select criteria).
So the correct query should look something like this:
select * from department
left join
(
select
building1.street, building1.streetno, building1.plz, building1.city, dept1.departmentid
from
department dept1
left join
supporter sup
on
dept.supporterid = sup.id
left join
building building1
on
sup.buildingid = building1.ibuildingid
where
dept.usepostaladresssupporter = 1
union all
select
building2.street, building2.streetno, building2.plz, building2.city, dept2.departmentid
from
building building2
right join
tueks_department dept2
on
dept2.buildingid = building2.ibuildingid
where
dept2.usepostaladresssupporter = 0
) postadress
on
department.departmentid = postadress.departmentid;
Your query will go wrong on data something like this:
Departmentid BuildingId Name
1 1 Dept1
2 2 Dept2
3 2 Dept3
The multiplying effect is not quite equal to deptcount * deptcount, but rather it is buildingcount * buildingcount + deptcount - buildingcount