I'm trying to join some data together from 2 tables, but on several columns. here's an example:
Source table
ID | Desc| AAAA| BBBB|
Table2 table
ID | Text| ID1 | ID2 | ID3 |
where ID1, ID2 and ID3 in Table2 are ID's from the Source table
I'd like to do a query which yields the results:
Table2.Text,
Source.Desc(ID1),
Source.AAAA(ID1),
Source.Desc(ID2),
Source.AAAA(ID2),
Source.Desc(ID3),
Source.AAAA(ID3)
I'd guess this would be a join, but i can't get the syntax right... or would I be better off with a Union?
You could just use multiple joins, couldn't you? For example:
SELECT tb.Desc, s1.Desc, s1.AAAAA, s2.Desc, s2.AAAAA, s3.Desc, s3.AAAA
FROM Table2 tb
INNER JOIN Source s1 ON tb.ID1 = s1.ID
INNER JOIN Source s2 ON tb.ID2 = s2.ID
INNER JOIN Source s3 ON tb.ID3 = s2.ID
You need to join to the source table three times, one for each ID. You could also try a unuion to see which performs better.
This is a bad table design (it should be normalized) and I would suggest you change it now if at all possible. There shoudl bea related table with each id in a separate record, then you could join once and it would be much more efficient and far easier to write code against and you wouldn't have to change the table structure and allthe queries the day you need ID4.
If not all the Source tables are populated in the Table2, this will still give you partial results:
SELECT
t.Desc, s1.Desc, s1.AAAAA, s2.Desc, s2.AAAAA, s3.Desc, s3.AAAA
FROM Table2 t
LEFT OUTER JOIN Source s1 ON t.ID1 = s1.ID
LEFT OUTER JOIN Source s2 ON t.ID2 = s2.ID
LEFT OUTER JOIN Source s3 ON t.ID3 = s2.ID
WHERE t.ID=#YourIDHere
Three joins should do the trick:
select A.*, coalesce(B1.Text,B2.Text,B3.Text,'') as Text
from Source A
inner join Table2 B1 on B1.ID1=A.ID
inner join Table2 B2 on B2.ID2=A.ID
inner join Table2 B3 on B3.ID3=A.ID
Related
I have a Join statement on two tables(Table 1 and 2), which returns the City and State. I have another table(Table 3) which contains columns like Name, City, State, Country. I want to fetch all the rows from Table 3 whose City and State Columns matches with the rows of the Join result.
Select * from 3rdTable where City='' AND State='';
Result from Join is like
- City | State
- A | B
- C | D
- E | F
Example Result if only 1 row of the 3rd table matches
- C | D
How can this be done?
You can use the joined table as a sub table in 3rdTable to create a where clause as follows;
select *
from 3rdTable
where City+'|'+State= (select a.City+'|'+b.State
from a
inner join b
on a.x=b.y)
Buy concatenating the fields, you can create a single equality to the joined subquery
Be sure about the joins, we have inner join, Left join, right join and outer join; maybe knowing the difference can help you to answer your question.
and also the code is not clear :)
Just join in the 3rd table...
IF we assume table1 has both city and state in it...
SELECT A.City, A.State
FROM Table1 A
INNER JOIN table2 B
on A.PK = B.A_FK
INNER JOIN table3 C
on A.City = C.City
and A.State = C.State
This is the nature of an inner join: Include all rows from all tables where the joined data matches.
If you use an OUTER join (left, right, full outer) then you get all records from one table and only those that match in the others, or full outer all records from all tables aligned where they match.
SELECT *
FROM table3 t3
INNER JOIN (SELECT city,
state
FROM table1 T1
JOIN table2 t2
ON t1.id = t2.id) a1
ON t3.city = a1.city
AND t3.state = a1.state
I think this could help you:
SELECT T3.*
FROM
table_1_2_join T12 /* replace this placeholder table with the select statement that joins your 2 tables */
JOIN table_3 T3 ON T3.City = T12.city AND T3.state = T12.state
Let me know if you need more details.
I ve post a pic of what im trying to accomplish ive been trying all the codes i can find online but nothing seems to work.
here a snippet of the code i'm trying to use.. Am i even on the right track? PS. its an oracle DB
SELECT
q1.x, q1.y, q2.z, ...
FROM
(SELECT ... FROM ...) q1
LEFT JOIN
(SELECT ... FROM ...) q2
ON q1.column = q2.column
thank you for help!
Unless I'm missing something profound, this is just two joins:
select t1.*, t2a.text as text1, t2a.text as text2
from t1 join
t2 t2a
on t2a.num = t1.num1 join
t2 t2b
on t2b.num = t1.num2;
You need to join Table 2 twice, once on Table1.NUM1 and once on Table1.NUM2:
SELECT
t1.A, t1.NUM1, t1.NUM2, t2a.TEXT AS TEXT1, t2b.TEXT AS TEXT2
FROM
Table1 t1
INNER JOIN Table2 t2a
ON t1.NUM1 = t2a.NUM
INNER JOIN Table2 t2b
ON t1.NUM2 = t2b.NUM
You can also use LEFT JOINS, if rows from Table 2 are missing and you still want to include the rows of Table 1 in such cases.
In order to be able to identify the 2 instances of Table 2 you need to give them different aliases. The alias on Table 1 is just for convenience.
I have 4 tables with one column is common on all tables. Is there a way to create a view where I can join all tables by same column where I see the common column only once.
Let's say I have table1
Cust ID | Order ID | Product_Name
Table2
Cust_ID | Cust_Name | Cust_Address
Table3
Cust_ID | Cust_Acc | Acc_Type
Table4
Cust_ID | Contact_Phone | Cust_Total_Ord
Here is the code I use to join tables;
SELECT *
FROM table1
LEFT JOIN table2 ON table1.Cust_ID = table2.Cust_ID
LEFT JOIN table3 ON table2.Cust_ID = table3.Cust_ID
LEFT JOIN table4 ON table3.Cust_ID = table4.Cust_ID
I get all tables joined by I see Cust_ID from each table as below;
Cust ID| Order ID|Product_Name| Cust_ID| Cust_Name|Cust_Address| Cust_ID| Cust_Acc| Acc_Type|Cust_ID|Contact_Phone|Cust_Total_Ord
Is there a way to remove duplicate Cust_ID columns or do I need to write each column name in the SELECT? I have more than 50 columns in total so will be difficult to write all.
Sorry if it is a really dumb question, I have checked previous similar questions but couldn't figure out and thanks for help.
you have common columns on all tables so could use using(common_column) to remove duplicated columns.
SELECT *
FROM table1
LEFT JOIN table2 using(Cust_ID)
LEFT JOIN table3 using(Cust_ID)
LEFT JOIN table4 using(Cust_ID)
I hop that useful.
you need to select columns from three tables first and then make inner join like below
select
t1.cust_id, t1.col1, t1.col2,
t2.col1_table2, t2.col2_table2,
t3.col1_table3, t3.col2_table3
from
table1 t1
inner join
table2 t2 on t1.cust_id = t2.cust_id
join table3 t3 on t1.cust_id = t3.cust_id
Result as shown in below image
No, you cannot easily do what you want in SQL Server. In other databases, you can use the using clause.
One thing you can do is select the columns explicitly from all but the first table:
SELECT t1.*, . . .
FROM table1 t1 LEFT JOIN
table2 t2
ON t1.Cust_ID = t2.Cust_ID LEFT JOIN
table3
ON t1.Cust_ID = table3.Cust_ID LEFT JOIN
table4
ON t1.Cust_ID = table4.Cust_ID;
Perhaps more important than the column issue, I changed the join conditions. You are using LEFT JOIN, so the first table is the "driving" table. When you say t2.Cust_ID = t3.Cust_Id, this returns true only when there was a match to table2. In general, you want to use the columns from table1, because it is the first one in the chain of LEFT JOINs.
I have 2 select statements having a common column POL.SP_NUM which I wish to combine. I am new to SQL and haven't the slightest clue how to go about with the same.
Query 1:
select POL.SP_NUM POL#
, POL.ASSET_NUM COV#
, count(distinct(POLX.ATTRIB_06)) COUNT_ADDENDA
, count(distinct(POLX.ATTRIB_07)) COUNT_CERT
, sum(POL.QTY) SI
from S_ASSET POL
, S_ASSET_X POLX
Where POL.ROW_ID = POLX.ROW_ID
and POL.SP_NUM in ('000','111','222')
group by
POL.SP_NUM
, POL.ASSET_NUM
Query 1 output:
POL# COV# COUNT_ADDENDA COUNT_CERT SI
000 856 2 0 1000
111 123 0 0 500
222 567 0 1 2000
Query 2:
select POL#, sum(DOCI)
from (
select POL.SP_NUM POL#, sum(Q.AMT + POL.AMT) DOCI
from S_ASSET POL
, S_QUOTE_ITEM Q
where POL.X_QUOTE_ID = Q.ROW_ID
and POL.SP_NUM in ('000','111','222')
group by POL.SP_NUM
UNION ALL
select POL.SP_NUM POL#, sum(QXM.AMT) DOCI
from S_ASSET POL
, S_QUOTE_ITEM Q
, S_QUOTE_ITEM_XM QXM
where POL.X_QUOTE_ID = Q.ROW_ID
and Q.ROW_ID = QXM.PAR_ROW_ID
and POL.SP_NUM in ('000','111','222')
group by POL.SP_NUM
)
group by POL#
Query 2 output:
POL# sum(DOCI)
000 90
111 0
222 10
Desired output:
POL# COV# COUNT_ADDENDA COUNT_CERT SI sum(DOCI)
000 856 2 0 1000 90
111 123 0 0 500 0
222 567 0 1 2000 10
If there is a better way to code this? Suggestions are welcome.
This is no answer to the question, but an answer to the request to explain the join types made in the comments setion.
INNER JOIN (or short: JOIN)
select * from t1 join t2 on t1.colx = t2.coly
only gives you matches. This is the most common join. You could replace the ON clause with a USING clause in case the columns in the ON clause have the same names in the tables. Sometimes usefull to quickly write a query, but I would generally not recommend USING.
LEFT OUTER JOIN (or short: LEFT JOIN)
select * from t1 left join t2 on t1.colx = t2.coly
gives you all t1 records, no matter whether they have a math in t2. So when there is a match or more for a t1 record, then you join these just as wih an inner join, but when a t1 record has no match in t2 then you get the t1 record along with an empty t2 record (all columns are NULL, even the columns you used in the ON clause, which is t2.coly in above example). In other words: you get all records you'd get with an inner join plus all t1 records that have no match in t2.
You can also use a RIGHT JOIN so you'd keep t2 records when there is no t1 match:
select * from t1 right join t2 on t1.colx = t2.coly
but this is regarded less readable by many people, so better don't use right outer joins, but simply swap tables then:
select * from t2 left join t1 on t1.colx = t2.coly
FULL OUTER JOIN (or short: FULL JOIN)
select * from t1 full outer join t2 on t1.colx = t2.coly
this gives you all records from both t1 and t2, no matter whether they have a match in the other table or not. Again: You get all records you'd get with an inner join plus all t1 with no t2 match plus all t2 with no t1 match.
When having several full outer joins the USING clause can come in handy:
select product, sum(p1.amount), sum(p2.amount), sum(p3.amount)
from p1
full outer join p2 using (product)
full outer join p3 using (product);
CROSS JOIN
A cross join joins a table without any criteria, so as to combine each of its records with each of the records already present. This is used to get all combinations and usually followed by a left outer join:
select products.product_id, regions.region_id, count(*)
from products
cross join regions
left join sales on sales.product_id = products.product_id
and sales.region_id = regions.region_id
group by products.product_id, regions.region_id
order by products.product_id, regions.region_id;
This gives you all possible combinations of products and regions and counts the sales therein. So you get a result record even for product / region combinations where nothing was sold (i.e. no entry in table sales).
NATURAL JOIN
looks at common column names to magically join tables. My simple advice: never use this join type.
ANTI JOIN
This is not a join type actually, but a usage of a join, namely an outer join. Here you want to get all records from a table except the matches. You achieve this by outer-joining the tables and then removing matches in the where clause.
select t1.*
from t1
left join t2 on t1.colx = t2.coly
where t2.coly is null;
This looks queer, because we have EXISTS (and IN) to check for existence:
select *
from t1
where not exists (select * from t2 where t2.coly = t1.colx);
So why would one obfuscate things and use the anti join pattern instead? It is a trick used on weak DBMS. When a DBMS is written, joins are the most important thing and the developers of the DBMS put all their effort into making them fast. They may neglect EXISTS and IN at first and only later care about their performance. So it may help then to use a join technique (the anti join) instead. My recommendation: Only use the anti join pattern when running into performance issues with a straight-forward query. So far I've never had to use anti joins it in more than twenty years. (It's good to have that option though. And it's good to know about them, so as to not be confused when stumbling upon such query some time :-)
You can join the queries:
select *
from (your query 1 here) query1
join (your query 2 here) query2 on query2.pol# = query1.pol#;
The same with WITH clauses:
with query1 as (your query 1 here),
query2 as (your query 2 here)
select *
from query1
join query2 on query2.pol# = query1.pol#;
I have four tables:
T1
ID ID1 TITLE
1 100 TITLE1
2 100 TITLE2
3 100 TITLE3
T2
ID TEXT
1 LONG1
2 LONG2
T3
ID1 ID2
100 200
T4
ID4 ID2 SUBJECT
1 200 A
2 200 B
3 200 C
4 200 D
5 200 E
I want output in this result format:
TITLE TEXT SUBJECT
TITLE1 LONG1 A
TITLE2 LONG2 B
TITLE3 null C
null null D
null null E
So I made this query but it gives me much more results than it should be.On example titles asre displayed more times than just once etc.
SELECT
t1.title,
t2.text,
t4.subject
FROM t1
LEFT OUTER JOIN t2 ON t1.id=t2.id
INNER JOIN t3 ON t1.id1=t3.id1
LEFT OUTER JOIN t4 ON t4.id2=t3.id2
WHERE
t1.id1=100
Thanks for help
Disclaimer: I don't work with DB2. After some browsing through documentation I have found that DB2 supports row_number() and full outer join, but I might easily be wrong.
To get rid of n:m relationship one has to build additional key. In this case simple solution is to add row number to each record in t1 and t4 and use it as join condition. Row_number does just that, produces numbers for groups of data defined by partition by in ascending sequence in order defined by order by.
As there is difference in number of records in t1 and t4, and it is unknown which one always has more records, I use full outer join to join them.
You can see the test (Sql Server version) # Sql Fiddle.
select t1_rn.title,
t2.[text],
t4_rn.subject
from
(
select t1.id,
t1.title,
t1.id1,
t3.id2,
row_number() over(partition by t1.id1
order by id) rn
from t1
inner join t3
on t1.id1 = t3.id1
) t1_rn
full outer join
(
select t4.subject,
t3.id1,
t4.id2,
row_number() over(partition by t4.id2
order by id4) rn
from t4
inner join t3
on t4.id2 = t3.id2
) t4_rn
on t1_rn.id1 = t4_rn.id1
and t1_rn.id2 = t4_rn.id2
and t1_rn.rn = t4_rn.rn
left join t2
on t1_rn.id = t2.id
This kind of work should definitely be done on presentation side of an application, but I believe that software you are using requires already prepared data.
try this :
select t1.title,t2.text,t4.subject
from t4
left join t3
on t4.id2=t3.id2
left join t1
on t1.id1=t3.id1
left join t2
on t1.id=t2.id
where t1.id=100
You should change your tables. Your last join does that to your output -just analyze your query. for every record from T1 you have every record from T4.
Outer joins are guaranteed to replicate rows, instead of matching only the ones you need. You may want to look at this:
http://blog.sqlauthority.com/2009/04/13/sql-server-introduction-to-joins-basic-of-joins/
To understand what the join types are, and how you can use them.
You are looking for a list of subjects, with associated text and title, but this may not be unique; more than one null exist for each of the titles. You want to drive the join from table 4, and get a list of subjects, with associated titles for each.
Looking at your ouput it appears you want all subjects displayed. Knowing this you should first off build everything off this table.
SELECT columns
FROM T4
Next build up your inner joins.
SELECT columns
FROM T4 subjectTable
INNER JOIN T3 mapTable
ON mapTable.ID2 = subjectTable.ID2
When happy with them, add on your optional columns with the outer join.
SELECT columns
FROM T4 subjectTable
INNER JOIN T3 mapTable
ON mapTable.ID2 = subjectTable.ID2
LEFT OUTER JOIN T2 textTable
ON textTable.ID = subjectTable.ID4
LEFT OUTER JOIN T1 titleTable
ON titleTable.ID1 = mapTable.ID1
WHERE
subjectTable.ID = 100;