Joining Three tables at the same time? [duplicate] - sql

This question already has answers here:
SQL JOIN and different types of JOINs
(6 answers)
Closed 7 years ago.
I have a table with multiple transaction types. Currently I'm only pulling the adjustments and payments, but I am needing to match the IDs of the types to their descriptions. For example, my transactions table has paytype_id and adjustment_id which range 1-100 for each. I have two other tables dbo.paytype and dbo.adjustments that have the distinct paytype_id and adjustment_id along with the pay_desc and adj_desc fields that describe what kind they are. Issue I'm running into is that any given transaction will only have a paytype_id or an adjustment_id but not both. So if I attempt to join one table, then the other I lose the NULL values of the secondary IDs
This query will pull the paytype_id descriptions but will remove any transactions with adjustment_id due to the payment_id being NULL for them.
SELECT
t.tran_num, t.resp_party_id, t.Total,
t.paytype_id, t.adjustment_id, t.clinic,
t.date_entered, p.pay_desc
FROM
adjpay_vw t
CROSS JOIN
paytype p
WHERE
(t.paytype_id = p.paytype_id AND t.clinic = p.clinic)
So I'm wondering how I can pull both the adj_desc from dbo.adjustments and the pay_desc from dbo.paytype

By having your join condition in the WHERE, it forces it to behave like an INNER JOIN. Instead of using the WHERE, add it to the JOIN condition and flip to a LEFT JOIN.
SELECT t.tran_num, t.resp_party_id, t.Total, t.paytype_id, t.adjustment_id, t.clinic, t.date_entered, p.pay_desc, adj.adj_desc, ISNULL(p.pay_desc,adj.adj_desc) [Description]
FROM adjpay_vw t
LEFT JOIN paytype p ON t.paytype_id=p.paytype_id AND t.clinic=p.clinic
LEFT JOIN dbo.adjustments adj ON adj.adjustment_id = t.adjustment_id
Also, since I wasn't sure your view contained the adjustment description, I've added a join for that and added both descriptions and a new columns that shows the description no matter if it was an adjustment or payment.

Related

Joining 3 tables in Sqlite and not receiving expected output

I understand similar question have been posted, however my issue isn't an error rather the lack of the desired result. I'm trying to join 3 tables each with 10,000 observations and combine them in the one table, however when i use inner join the observations reduce to little over 4000. I understand that INNER JOIN is essentially an intersection but I'm expecting 10,000 observations and based on my code I don't see how that is occurring. Here is my code:
SELECT *
FROM Characteristics
INNER JOIN Prices ON Prices.pid = Characteristics.pid
INNER JOIN Locations ON Locations.tid = Characteristics.tid
;
CHARACTERISTICS
||Property_Id|| ||Beds|| ||Baths|| ||Type_ID||
PRICES
||Price|| ||Year|| ||Property_ID||
LOCATIONS
||Type_ID|| ||X coord|| ||Y coord||
Those are representative of the tables I didn't include numbers because of formatting issues but as you can imagine the number contained in Property_id and Type_id are the same for all columns regardless of table, what i would like is one table with each of the respective columns containing 10,000 rows, i've checked for NA values on R and they're all of the same length.
If you want to keep all characteristics -- even when there are no matches in the other tables -- then use left join:
SELECT *
FROM Characteristics c LEFT JOIN
Prices p
ON p.pid = c.pid LEFT JOIN
Locations l
ON l.tid = c.tid;

How to join 4 tables in SQL?

I just started using SQL and I need some help. I have 4 tables in a database. All four are connected with each other. I need to find the amount of unique transactions but can't seem to find it.
Transactions
transaction_id pk
name
Partyinvolved
transaction.id pk
partyinvolved.id
type (buyer, seller)
PartyCompany
partyinvolved.id
Partycompany.id
Companies
PartyCompany.id pk
sector
pk = primary key
The transaction is unique if the conditions are met.
I only need a certain sector out of Companies, this is condition1. Condition2 is a condition inside table Partyinvolved but we first need to execute condition1. I know the conditions but do not know where to put them.
SELECT *
FROM group
INNER JOIN groupB ON groupB.group_id = group.id
INNER JOIN companies ON companies.id = groupB.company_id
WHERE condition1 AND condition2 ;
I want to output the amount of unique transactions with the name.
It is a bit unclear what you are asking as your table definitions look like your hinting at column meanings more than names such as partycompany.id you are probably meaning the column that stores the relationship to PartyCompany column Id......
Anyway, If I follow that logic and I look at your questions about wanting to know where to limit the recordsets during the join. You could do it in Where clause because you are using an Inner Join and it wont mess you your results, but the same would not be true if you were to use an outer join. Plus for optimization it is typically best to add the limiter to the ON condition of the join.
I am also a bit lost as to what exactly you want e.g. a count of transactions or the actual transactions associated with a particular sector for instance. Anyway, either should be able to be derived from a basic query structure like:
SELECT
t.*
FROM
Companies co
INNER JOIN PartyCompancy pco
ON co.PartyCompanyId = pco.PartyCompanyId
INNER JOIN PartyInvolved pinv
ON pco.PartyInvolvedId = pinv.PartyInvolvedId
AND pinv.[type] = 'buyer'
INNER JOIN Transactions t
ON ping.TransactionId = t.TransactionId
WHERE
co.sector = 'some sector'

SQL Query Results Using Joins

I'm trying to do this query to display the names of the stores and the quantity of each book sold with only using joins but I tried to use
SELECT DISTINCT x.stor_name, t.title, s.qty
FROM stores x
INNER JOIN discounts d
ON x.stor_id=d.stor_id
INNER JOIN salesdetail s
ON d.stor_id=s.stor_id
INNER JOIN titles t
ON s.title_id=t.title_id
ORDER BY s.qty desc;
but that only displayed one of the stores results set for 'Bookbeat'.
I tried to use Left, Right & Full Outer joins to no avail so I'm wondering how I would go about doing that query to display the names for the other stores that are not displaying their result set. As there is 7 stores and only 1 is displaying it's results.
The link is a pastebin to the database.
And this is the schema.
It's hard to say without more information about your schema - it strikes me as wrong-ish that you're joining to discounts only on stor_id. I'd expect discounts to be applied to different titles, not store-wide... and I wouldn't expect discounts to be always-enabled. Try running it without the discounts inner join. Futzing around with "Distinct" and outer joins is almost always the wrong approach with things like this
I see from your profile you're a first-year. Is this schoolwork? How do I ask and answer homework questions?

How to combine two tables, one with 1 row and one with n rows?

I have a database with two tables
One with games
and one with participants
A game is able to have more participants and these are in a different table.
Is there a way to combine these two into one query?
Thanks
You can combine them using the JOIN operator.
Something like
SELECT *
FROM games g
INNER JOIN participants p ON p.gameid = g.gameid
Explanation on JOIN operators
INNER JOIN - Match rows between the two tables specified in the INNER
JOIN statement based on one or more
columns having matching data.
Preferably the join is based on
referential integrity enforcing the
relationship between the tables to
ensure data integrity.
o Just to add a little commentary to the basic definitions
above, in general the INNER JOIN
option is considered to be the most
common join needed in applications
and/or queries. Although that is the
case in some environments, it is
really dependent on the database
design, referential integrity and data
needed for the application. As such,
please take the time to understand the
data being requested then select the
proper join option.
o Although most join logic is based on matching values between
the two columns specified, it is
possible to also include logic using
greater than, less than, not equals,
etc.
LEFT OUTER JOIN - Based on the two tables specified in the join
clause, all data is returned from the
left table. On the right table, the
matching data is returned in addition
to NULL values where a record exists
in the left table, but not in the
right table.
o Another item to keep in mind is that the LEFT and RIGHT OUTER
JOIN logic is opposite of one another.
So you can change either the order of
the tables in the specific join
statement or change the JOIN from left
to right or vice versa and get the
same results.
RIGHT OUTER JOIN - Based on the two tables specified in the join
clause, all data is returned from the
right table. On the left table, the
matching data is returned in addition
to NULL values where a record exists
in the right table but not in the left
table.
Self -Join - In this circumstance, the same table is
specified twice with two different
aliases in order to match the data
within the same table.
CROSS JOIN - Based on the two tables specified in the join clause, a
Cartesian product is created if a
WHERE clause does filter the rows.
The size of the Cartesian product is
based on multiplying the number of
rows from the left table by the number
of rows in the right table. Please
heed caution when using a CROSS JOIN.
FULL JOIN - Based on the two tables specified in the join clause,
all data is returned from both tables
regardless of matching data.
example
table Game has columns (gameName, gameID)
table Participant has columns (participantID, participantName, gameID)
the GameID column is the "link" between the 2 tables. you need a common column you can join between 2 tables.
SELECT gameName, participantName
FROM Game g
JOIN Participat p ON g.gameID = p.gameID
This will return a data set of all games and the participants for those games.
The list of games will be redundant unless you structure it some other way due to multiple participants to that game.
sample data
WOW Bob
WOW Jake
StarCraft2 Neal
Warcraft3 James
Warcraft3 Rich
Diablo Chris

MySQL - Combining questions and answers from multiple transactions

I have the following tables within a database, that I am using to store the results of surveys:
Each time I speak to someone at a store (read Shop), I create a new transaction, with a date/time (tblTransaction.Created). Each transaction can have many question answers associated with it.
My problem is that 2 transactions could both contain different answers to the same question and I am trying to create an SQL query/procedure to return only the latest question answers for a given store.
Here's an example:
I speak with someone at Some Shop Plc. and create a transaction on the 01/01/09 (transaction ID 1). In this transaction, I ask QuestionIDs 1 and 2. Then on the 10/01/09 I speak to them again, creating a new transaction (transaction ID 2) and answer questions 2 and 3.
I want to be able to show the list of latest answers; Question 1 from the first transaction and questions 2 and 3 from the second transaction.
SELECT
S.StoreID,
S.BranchName,
A.QuestionID,
T.Created,
A.*
FROM
tblStore S
INNER JOIN tblTransaction T ON
T.StoreID = S.StoreID
INNER JOIN tblAnswer A ON
A.TransactionID = T.TransactionID AND
A.StoreID = S.StoreID
WHERE NOT EXISTS
(
SELECT
T2.StoreID,
A2.QuestionID,
T2.TransactionID,
T2.CreatedDate
FROM
tblTransaction T2
INNER JOIN tblAnswer A2 ON
A2.TransactionID = T2.TransactionID AND
A2.StoreID = T2.StoreID
WHERE
T2.StoreID = T.StoreID AND
A2.QuestionID = A.QuestionID AND
T2.CreatedDate > T.CreatedDate
)
You can also do this by LEFT OUTER JOINing the subquery on the same criteria as in the WHERE clause and looking for a NULL value in it or you can remove the TransactionID from the subquery use a MAX() on the CreatedDate and look for a match that way with an INNER JOIN.
Keep in mind that this may not act how you are expecting if you have multiple transactions for the same store with the same created date. You may need to add an additional criteria there based on your business rules around that situation.