How do I join 2 tables in SQL Server - sql-server

I have two tables as follows that the id values of the tblBranch table in the tblPost table are in the Cityid, catid, Desid columns
How can I join these two tables together to see the values of cityid, catid, Desid?
tblBranch tblPost
---------- -----------
id id
Name title
cityid
catid
Desid

When you are join tables, you are bringing/combine TWO TABLES data rows
and their columns into ONE BIG TABLE base on the MATCHING JOIN COLUMNS.
Here is example of inner join:
tblDepartment
--------------
id_Dept NameDept
1 Math
2 Physic
tblTeacher
----------
id_Teacher FullName id_Dept
1 Smith Adam 1
2 John Doe 1
3 Marry Doe 2
EXAMPLE 01: No rows filter
select TC.id_Teacher, TC.FullName, TC.id_Dept, TD.NameDept from tblTeacher TC inner join tblDepartment TD on TC.id_Dept = TD.id_Dept
Result ONE BIG TABLE OF JOINING TABLES
id_Teacher FullName id_Dept NameDept
1 Smith Adam 1 Math
2 John Doe 1 Math
3 Marry Doe 2 Physic
EXAMPLE 02: With rows filter
Result ONE BIG TABLE OF JOINING TABLES with SQL where clause to limit smaller set of data rows return
select TC.id_Teacher, TC.FullName, TC.id_Dept, TD.NameDept from tblTeacher TC inner join tblDepartment TD on TC.id_Dept = TD.id_Dept
where TC.id_Dept = 2
id_Teacher FullName id_Dept NameDept
3 Marry Doe 2 Physic
You can use the above example to see WHAT COLUMNS your table should join to return result with BIG TABLE

So if I understand you correctly, you want to take CityId, CatId and DesId from tblPost, and for each of them, you want to join to the tblBranch table and show the Name for that Id - correct?
In that case, you need a query like this:
SELECT
CityId,
CityName = brCity.Name,
CatId,
CatName = brCat.Name,
DesId,
DesName = brDes.Name
FROM
tblPost p
LEFT OUTER JOIN
tblBranch brCity ON p.CityId = brCity.Id
LEFT OUTER JOIN
tblBranch brCat ON p.CatId = brCat.Id
LEFT OUTER JOIN
tblBranch brDes ON p.DesId = brDes.Id
Basically, you need to have three joins - one for each of the Id in your tblPost table.
I chose to use LEFT OUTER JOIN to avoid eliminating a row completely, if one of the Id cannot be found/matched in the tblBranch table.

Related

do i need a certain join statement for my code

I'm stuck on writing this piece of code.
the output that i need to get is
firstName lastname Name Price Date
--------------- --------------- ------------------------- -------- ----------
Bateman Michael Furniture DR 222.80 2013-05-01
Tara Roswell Clothes Ladies 24.25 2013-05-04
LeMay Mike Toys Child 12.00 2013-05-12
Create a query that will show who picked up unsold items during the month of May 2013. Include in your output the first and last name of the owner, along with the name of the item, max price and pick up date. Order your output by Pick up date. My output looked like the following:
and my output is
FirstName LastName Name Price Date
--------------- --------------- ------------------------- ------- ----------
my code is
SELECT P.FirstName
, P.LastName
, IT.Name
, I.MaxPrice AS Price
, IP.Date
FROM People P
JOIN CHARITY C ON P.PeopleID = C.ContactID
JOIN Donation D ON C.CHARITYID = D.CHARITYID
JOIN Item_Donation ID ON D.DonationID = ID.DonationID
JOIN IteM I ON ID.ItemID = I.ItemID
JOIN Item_Type IT ON I.ItemTypeID = IT.ItemTypeID
JOIN Item_PickUp IP ON I.ItemID = IP.ItemID
ORDER BY IP.Date
I see nothing wrong with your query, so I suspect a data issue. Here is how I would investigate this. Start with querying the "root" table:
SELECT * FROM People p
If the results are not what you expect, then you have found the issue in your data.
If the results are ok, then add the first join:
SELECT *
FROM People P
JOIN CHARITY C ON P.PeopleID = C.ContactID
Same thing, if the results are not what you expect, then you have a data issue in the CHARITY table. Query the CHARITY table by itself to see why the rows from that table are not joining to People:
SELECT * FROM CHARITY
If the results are what you expect, then add the next JOIN, and continue, one JOIN at a time, until you find the one that causes no rows to be returned. Examine the data in that table to see why it doesn't join to your query before the join.

sql server duplicated result while getting data from multiple tables

Hi i have a small problem with SQL SERVER .
an building a Purchase and stokes system i want to retrieve data from 3 Tables:-
Tables Structure
Query:
SELECT Tbl_Products.Product_Name, Tbl_PurchaseDetails.BuyPrice, Tbl_PurchaseDetails.AllPieceBoxes, Tbl_PurchaseDetails.TotalPrice, Tbl_PurchaseHeader.purchaseOrder
FROM Tbl_Products
INNER JOIN Tbl_PurchaseHeader ON Tbl_Products.Product_ID = Tbl_PurchaseHeader.ProductId
INNER JOIN Tbl_PurchaseDetails ON Tbl_PurchaseHeader.purchaseOrder = Tbl_PurchaseDetails.PurchaseOrder
Query Result
Product_Name BuyPrice AllPieceBoxes TotalPrice purchaseOrder
-------------------- -------- ------------- ---------- -------------
Dell Alien-Ware 2500.000 5 12500.000 1
KINGSTON-Desktop 8GB 2500.000 5 12500.000 1
Dell Alien-Ware 95.00 10 950.000 1
KINGSTON-Desktop 8GB 95.00 10 950.000 1
Given the join below I think you have multiple rows for a given Product_ID in Tbl_PurchaseHeader which you then join with tbl_PurchaseDetails. For example if there are two rows in Tbl_PurchaseHeader with Product_ID of 1 then you will join with Tbl_PurchaseDetails twice so 1 Tbl_Products gives 2 Tbl_PurchaseHeader's which if there are multiple (say 3) rows in Tbl_PurchaseDetails then you'll get an additional 2 x 3 so 6 rows.
FROM Tbl_Products
INNER JOIN Tbl_PurchaseHeader ON Tbl_Products.Product_ID = Tbl_PurchaseHeader.ProductId
INNER JOIN Tbl_PurchaseDetails ON Tbl_PurchaseHeader.purchaseOrder = Tbl_PurchaseDetails.PurchaseOrder
Check out your data, do a singleton SELECT against each table and track the data through to see how many rows come back for a) Product_ID and then for PurchaseOrder.

Select mismatch column values from database

I want to select and fetch all mismatch value of two table having same Column Name But Id, Name and City are different. I am Using Sql Server Management Studio
Table A:
id Name City
1 John karachi
2 smith Capetown
3 liza Washington
Table B:
id Name City
7 Grey Dubai
8 Clarke Texas
9 liza Washington
OUTPUT:
7 Grey Dubai
8 Clarke Texas
This has been answered hundreds and hundreds of times. Not quite sure what you mean by "having same Column Name But Id, Name and City are different" but here are a couple of example of how you can do this.
You can use a left join where tablea is null,
select b.Name
, b.City
from tableb b
left join tablea a on a.name = b.name
and a.city = b.city
where a.name is null
You can use except.
select Name
, City
from tableb
except
select Name
, City
from tablea
You can try the below query. Assuming that the id column is never null
select tb.*
from tableB tb
left join tableA ta
on tb.Name=ta.Name and tb.City=ta.City
where ta.id is NULL
Link to demo sql fiddle: http://sqlfiddle.com/#!3/250e5/1

Get union of two table and taking data with a condition

I have two tables
table-a
id name
100 asd
101 ass
102 gdd
103 hgf
104 cvd
105 erf
table-b
id filter
100 red
101 blue
100 green
100 yellow
102 black
102 red
103 dark
Table-a is the master table and that have all the id's.but Table two is the one which has 'filter' data.
from these two table I want to find out all those 'id's which does not have minimum 2 filters.
note that table-b does not have all the itemnumbers in table-a, and i want all that itemnumber irrespective of if that is in table-a or table-b.I have tried inner joining these two tables and getting data out but nothing worked.
Select A.ID, A.Name, count(*)
from tableA A
LEFT JOIN tableB B on A.ID = B.ID
Group By A.ID, A.name
having count(*) <= 1
LEFT JOIN gives all records from A and only those in B which match.
The group by ID and name let us count the number of filters found in
each
The having says give me any items with a count less than or
equal to 1. (or less than the minimum 2)
Thus results would be.
101 ass 1
103 hgf 1
104 cvd 0
105 erf 0
select
*
from
table-a a
left join (
select id, count(id) as c from table-b group by id
) v on a.id = v.id
where isnull(v.id, 0) < 2
I think this would work in SQL Server (tested in SQLite and usually the two are fairly compatible when it comes to inline view syntax). But syntax issues aside, inline views can make working with sets easier to visualize.
select TA.id, name
from TA
inner join
(
select id from TA
where not exists (select id from TB where TA.id = TB.id)
UNION
select id from TB
group by id having count(filter) < 2
) as FOO
on TA.id = FOO.id
The default behavior of UNION is to remove duplicates.
The first UNIONed set consists of the ids from table A that have no filter (no counterpart in the filters table B).
The second UNIONed set consists of the ids from the filters table, table B, that have only 1 filter.
We inner join those unioned sets back to Table A to get the entity Name.

SQL View - Combine multiple rows into 1 row

I am trying to make a new view using in MSSql 2008 from three tables:
Table 1 has customer id and transaction id
Table 1
CustomerID TransactionID
1 1
1 2
Table 2 has Purchases Transaction and Products ID
TransactionID ProductID
1 x
2 y
Table 3 has Products Names
ProductID Name
1 x
2 y
I view I would like to make should show
CustomerID Product Name
1 x, y
When I use the following query:
SELECT table1. CustomerID, table3.Name
FROM table1 LEFT OUTER JOIN
Table2 ON table2. TransactionID = table1.VisitId LEFT OUTER JOIN
Table3 ON table2. ProductID = Table3. ProductID
GROUP BY table1. CustomerID, table3.Name
I get
CustomerID Product Name
1 x
1 y
Thanks in Advance
One way to do this is to use a user defined function, something like:
SELECT table1.CustomerID, dbo.BuildStringOfCustomerProductNames(table1.CustomerID)
FROM table1
And create a user defined function like: dbo.BuildStringOfCustomerProductNames
that takes a customerid as input.
Inside there, you can run a query to loop through the table 2 and table 3 joined records to make a string, and return that.
Off hand I can't think of any other simple way to do it.

Resources