Join 3 tables using column common to all 3 tables - sql

I am a total SQL novice, so please bear with me. I have three tables that are set up in the following fashion:
date|country|Test 1|Test 2|Test 3|etc.
The data in the date and country columns are identical across the three tables, and the differences are in the data in the Test columns. I'd like to use Join to query one date column and the three corresponding Test columns from the three tables.
I'm planning on just re-building the table so that the Test columns in the other tables are additional columns in the one table, but I'd still like to know how to use Join in this way. This is what I have at the moment, although it's throwing an error saying that there's an error in the syntax of the FROM clause. It's worth noting that I'm running this query in VBA using an Access DB.
SELECT r.CRDate, r.Test, p.Test, z.Test
FROM CountryRaw as r
INNER JOIN CountryPct as p ON p.CPctDate = r.CRDate
INNER JOIN CountryZ as z ON z.CZDate = p.CPctDate
WHERE r.Country = 'US' AND p.Country = 'US' AND z.Country = 'US'
I came across something using SELECT COALESCE(r.CRDate, p.CPctDate, z.CZDate) to start, but I didn't get anywhere with that.

MS Access requires extra parentheses. So try this:
SELECT r.CRDate, r.Test, p.Test, z.Test
FROM (CountryRaw as r INNER JOIN
CountryPct as p
ON p.CPctDate = r.CRDate
) INNER JOIN
CountryZ as z
ON z.CZDate = p.CPctDate
WHERE r.Country = 'US' AND p.Country = 'US' AND z.Country = 'US'

Related

Conditional join that changes number of join conditions

I am trying to join data based on the following scenario.
Let's say there are two businesses. Business 1 has one field for customer data, business 2 has two fields. I need to join to multiple other tables using these customer fields.
I would like to create a join that joins on just field 1 for business 1, but field 1 AND field 2 for business 2. In other words, there is a more granular identifier available for business 2, but it is still valid to join on just field 1 for business 1 as well. It also needs to function like an inner join, in that we are only preserving the relevant data that match these conditions.
The code would look something like this for business 1:
FROM customer_data a
INNER JOIN marketing_data b
ON a.member_number = b.member_number
WHERE business_number = 1
And something like this for business 2:
FROM customer_data a
INNER JOIN marketing_data b
ON a.member_number = b.member_number
AND a.sub_member_number = b.sub_member_number
WHERE business_number = 2
I am hoping to extract both sets of data in one join statement. Also, just in case it helps, I am using the Snowflake platform to write my queries.
Following should work for both the cases.
FROM customer_data a
INNER JOIN marketing_data b ON a.member_number = b.member_number
WHERE (
a.sub_member_number = b.sub_member_number
AND business_number = 2
)
OR business_number = 1
You can put the conditions in the ON clause like this:
FROM customer_data cd INNER JOIN
marketing_data md
ON cd.member_number = md.member_number AND
( cd.business_number <> 2 OR
cd.sub_member_number = md.sub_member_number
)
Note: this generalizes beyond just businesses 1 and 2, with the special condition only applying to 2. The first condition can be = 1 if you want to be more specific.
Also note that this introduces meaningful table aliases rather than arbitrary letters. This makes queries much easier to understand.

SQL Server : multi-join with tuple IN clause

I'm trying to join 4 tables that have a somewhat complex relationship. Because of where this will be used, it needs to be contained in a single query, but I'm having trouble since the primary query and the IN clause query both join 2 tables together and the lookup is on two columns.
The goal is to input a SalesNum and SalesType and have it return the Price
Tables and relationships:
sdShipping
SalesNum[1]
SalesType[2]
Weight[3]
sdSales
SalesNum[1]
SalesType[2]
Zip[4]
spZones
Zip[4]
Zone[5]
spPrices
Zone[5]
Price
Weight[3]
Here's my latest attempt in T-SQL:
SELECT
spp.Price
FROM
spZones AS spz
LEFT OUTER JOIN
spPrices AS spp ON spz.Zone = spp.Zone
WHERE
(spp.Weight, spz.Zip) IN (SELECT ship.Weight, sales.Zip
FROM sdShipping AS ship
LEFT OUTER JOIN sdSales AS sales ON sales.SalesNum = ship.SalesNum
AND sales.SalesType = ship.SalesType
WHERE sales.SalesNum = (?)
AND ship.SalesType = (?));
SQL Server Management Studio says I have an error in my syntax near ',' (appropriately useless error message). Does anybody have any idea whether this is even allowed in Microsoft's version of SQL? Is there perhaps another way to accomplish it? I've seen the multi-key IN questions answered on here, but never in the case where both sides require a JOIN.
Many databases do support IN on tuples. SQL Server is not one of them.
Use EXISTS instead:
SELECT spp.Price
FROM spZones spz LEFT OUTER JOIN
spPrices spp
ON spz.Zone = spp.Zone
WHERE EXISTS (SELECT 1
FROM sdShipping ship LEFT JOIN
sdSales sales
ON sales.SalesNum = ship.SalesNum AND
sales.SalesType = ship.SalesType
WHERE spp.Weight = ship.Weight AND spz.Zip = sales.Zip AND
sales.SalesNum = (?) AND
ship.SalesType = (?)
);

How can I do a SQL join to get a value 4 tables farther from the value provided?

My title is probably not very clear, so I made a little schema to explain what I'm trying to achieve. The xxxx_uid labels are foreign keys linking two tables.
Goal: Retrieve a column from the grids table by giving a proj_uid value.
I'm not very good with SQL joins and I don't know how to build a single query that will achieve that.
Actually, I'm doing 3 queries to perform the operation:
1) This gives me a res_uid to work with:
select res_uid from results where results.proj_uid = VALUE order by res_uid asc limit 1"
2) This gives me a rec_uid to work with:
select rec_uid from receptor_results
inner join results on results.res_uid = receptor_results.res_uid
where receptor_results.res_uid = res_uid_VALUE order by rec_uid asc limit 1
3) Get the grid column I want from the grids table:
select grid_name from grids
inner join receptors on receptors.grid_uid = grids.grid_uid
where receptors.rec_uid = rec_uid_VALUE;
Is it possible to perform a single SQL that will give me the same results the 3 I'm actually doing ?
You're not limited to one JOIN in a query:
select grids.grid_name
from grids
inner join receptors
on receptors.grid_uid = grids.grid_uid
inner join receptor_results
on receptor_results.rec_uid = receptors.rec_uid
inner join results
on results.res_uid = receptor_results.res_uid
where results.proj_uid = VALUE;
select g.grid_name
from results r
join resceptor_results rr on r.res_uid = rr.res_uid
join receptors rec on rec.rec_uid = rr.rec_uid
join grids g on g.grid_uid = rec.grid_uid
where r.proj_uid = VALUE
a small note about names, typically in sql the table is named for a single item not the group. thus "result" not "results" and "receptor" not "receptors" etc. As you work with sql this will make sense and names like you have will seem strange. Also, one less character to type!

Joining tables based on values from other tables

I have the following tables. I want to run a query but I think my beginner tsql level won't help here.. It probably also is a situation where I have a bad database design.
Basically I need to select all fields from tblPhotoGalleries. Also I need to create a seperate field named GalleryCategoryName.
GalleryCategoryName field will be the pCatName in tblPhotoGalleryCats.
If pCatName in tblPhotoGalleryCats = '0', then that would mean, ConnectedNewsCatID is something other than 0. In that case;
GalleryCategoryName will be the CategoryName field from tblNewsCategories where CategoryID = ConnectedNewsCatID
Use a left join on the news category table, and use a case expression to choose between the names:
select
g.pgID, g.gName,
GalleryCategoryName = case c.pCatName when '0' then n.CategoryName else c.pCatName end
from tblPhotoGalleries g
inner join tblPhotoGFalleryCats c on c.pCatID = g.FK_pCatID
left join tblNewsCategories n on n.CategoryOd = c.ConnectedNewsCatID
Try starting here:
select *,
case when PGC.pCatName = '0' then NC.CategoryName else PGC.pCatName end as [CatName]
from tblPhotoGalleries as PG inner join
tblPhotoGalleryCats as PGC on PGC.pCatID = FK_pCatID left outer join
tblNewsCategories as NC on NC.CategoryId = ConnectedNewsCatID

SQL - Query Select Joins through multiple tables

Here is the situation:
I search for Persons with ID (empr.empr_cb)
that has bill(s) to pay (transactions.montant)
this refers to transactions.compte_id
which is identical to comptes.id_compte
this refers to comptes.proprio.id
which is identical to empr.id_empr
that would give us the Person ID (empr.empr_cb)
I tried this, but I don't know what joins to set (cross Join?):
SELECT `empr`.`empr_cb`,`transactions`.`montant`
FROM `empr`,`comptes`,`transactions`
WHERE `transactions`.`montant` > `0`
AND `transactions`.`encaissement` = `0`
AND `transactions`.compte_id` = `comptes`.`id_compte`
AND `comptes`.`proprio_id` = `id_empr`
Any ideas how to put the joins?
This query is already using implicit INNER JOINs. It can be rewritten this way:
SELECT empr.empr_cb
, transactions.montant
FROM empr
JOIN comptes ON comptes.proprio_id = empr.id_empr
JOIN transactions ON transactions.compte_id = comptes.id_compte
WHERE transactions.encaissement = 0
AND transactions.montant > 0