SQL - Join two query in same query with two rows - sql

i have one query that i need include the status in another row, i think that it's easy but i'm not remember it..
status
A
B
C
D
job
1
2
3
i want a output like:
job status
1 A
1 B
1 C
1 D
2 A
2 B
2 C
2 D
...
Can anyone help?

that is called CROSS JOIN
SELECT *
FROM status CROSS JOIN job;

I'm just guessing your table layout here because you did not give it in your question.
SELECT t1.job, t2.status
FROM t1 INNER JOIN t2 ON t1.something = t2.something
Note that if you had given the table structure something, t1 and t2 would actually be the real names.
If there is no particular key and you just want to match every value of t1.job to every value of t2.status then this will do the job:
SELECT t1.job, t2.status
FROM t1, t2

You might want to read a little bit about JOINs in SQL, here's a good resource:
http://www.w3schools.com/sql/sql_join.asp
As per your case, you can simply do:
SELECT * FROM job, status
Assuming that those are table names and these are the only columns in there.
EDIT:
Link with explanation on how CROSS JOIN works as well:
http://www.w3resource.com/sql/joins/cross-join.php

Related

Join two tables without relationship, add 1 to many

I've been frequenting this site for awhile now but this time, I didn't find any answers around this question so here goes.
I have two tables that do not have any PK/FK or relationship otherwise. What I am trying to do is the following.
Table 1
Column A
A
B
C
Table 2
Column B
1
2
3
Desired Result:
Combined Table
Column A Column B
A 1
A 2
A 3
B 1
B 2
B 3
C 1
C 2
C 3
Pretty much, for every value in the first table, append the full list of the second table until there's no more.
I hope this makes sense on what I am trying to achieve.
Thank you!
You need to use cross join:
SELECT ColumnA, ColumnB
FROM table1
CROSS JOIN table2
ORDER BY ColumnA;
As alluded to in other answers, you'll want to use CROSS JOIN which will give you the Cartesian product of the two tables:
SELECT t1.columnA, t2.columnB
FROM t1 CROSS JOIN t2;
You might see this expressed in older code like this:
SELECT t1.columnA, t2.columnB
FROM t1, t2;
"Cartesian product" is a term from mathematics: the Cartesian product of two sets X and Y (tables in relational databases are actually sets) is the set of all ordered pairs (x,y) where x in X and y in Y. In your case you are getting the Cartesian product of the sets all values of column A in t1 and all values of column B in t2.
Hope this helps.
This should do it:
SELECT ColumnA, ColumnB
FROM TableA
CROSS JOIN TableB
SELECT *
FROM Table1
CROSS JOIN Table2

SQL subquery to get all combination in two different selected sets

I have question to regarding a query I am writing:
I have two different (columns) data sets which I want to combine the result of, for instance:
Set 1: Set 2:
1 A
2 B
3 C
I want to create a query with the result:
resultset:
1 A
1 B
1 C
2 A
2 B
2 C
3 A
3 B
3 C
Is this possible using a JOIN or UNION?
So I get all possible combinations between the different rows?
Thank you for helping out!
What you want to do is a cartesian join
SELECT
S1.col1,
S2.col2
FROM
S1,S2
Please see the example in the fiddle
You are looking for cross join:
select t1.col1, t2.col1
from table1 t1 cross join
table2 t2
order by t1.col1, t2.col1;

SQL Server double left join counts are different

Code:
Select a.x,
a.y,
b.p,
c.i
from table1 a left join table2 b on a.z=b.z
left join table3 on a.z=c.z;
When I am using the above code I am not getting the correct counts:
Table1 has 30 records.
After first left join I get 30 records but after 2nd left join I am getting 33 records.
I am having hard time figuring out why I am getting different counts. According to my understanding I should be getting 30 counts even after the 2nd left join.
Can anyone help me understand this difference?
I am using sql server 2012
There are multiple rows in table3 with the same z value.
You can find them by doing:
select z, count(*)
from table3
group by z
having count(*) >= 2
order by count(*) desc;
If you want at most one match, then outer apply can be useful:
Select a.x, a.y, b.p, c.i
from table1 a outer apply
(select top 1 b.*
from table2 b
where a.z = b.z
) b outer apply
(select top 1 c.*
from table3 c
where a.z = c.z
) c;
Of course, top 1 should be used with order by, but I don't know which row you want. And, this is probably a stop-gap; you should figure out why there are duplicates.
In your table table3 contain more then 1 row per 1 row in table1. Check one value which is occured more times in both tables.
You can use group by with max function to make one to one row.

SQL - get max result

Assume there is a table name "test" below:
name value
n1 1
n2 2
n3 3
Now, I want to get the name which has the max value, I have some solution below:
Solution 1:
SELECT TOP 1 name
FROM test
ORDER BY value DESC
solution 2:
SELECT name
FROM test
WHERE value = (SELECT MAX(value) FROM test);
Now, I hope use join operation to find the result, like
SELECT name
FROM test
INNER JOIN test ON...
Could someone please help and explain how it works?
If you are looking for JOIN then
SELECT T.name, T.value
FROM test T
INNER JOIN
( SELECT T1.name, T1.value ,
RANK() OVER (PARTITION BY T1.name ORDER BY T1.value) N
FROM test T1
WHERE T1.value IN (SELECT MAX(t2.value) FROM test T2)
)T3 ON T3.N = 1 AND T.name = T3.name
FIDDLE DEMO
or
select name, value
from
(
select name, value,
row_number() over(order by value desc) rn
from test
) src
where rn = 1
FIDDLE DEMO
First, note that solutions 1 and 2 could give different results when value is not unique. If in your test data there would be an additional record ('n4', 3), then solution 1 would return either 'n3' or 'n4', but solution 2 would return both.
A solution with JOIN will need aliases for the table, because as you started of, the engine would say Ambiguous column name 'name'.: it would not know whether to take name from the first or second occurrence of the test table.
Here is a way to complete the JOIN version:
SELECT t1.name
FROM test t1
LEFT JOIN test t2
ON t2.value > t1.value
WHERE t2.value IS NULL;
This query takes each of the records, and checks if any records exist that have a higher value. If not, the first record will be in the result. Note the use of LEFT: this denotes an outer join, so that records from t1 that have no match with t2 -- based on the ON condition -- are not immediately rejected (as would be the case with INNER): in fact, we want to reject all the other records, which is done with the WHERE clause.
A way to understand this mechanism, is to look at a variant of the query above, which lacks the WHERE clause and returns the values of both tables:
SELECT t1.value, t2.value
FROM test t1
LEFT JOIN test t2
ON t2.value > t1.value
On your test data this will return:
t1.value t2.value
1 2
1 3
2 3
3 (null)
Note that the last entry would not be there if the join where an INNER JOIN. But with the outer join, one can now look for the NULL values and actually get those records in the result that would be excluded from an INNER JOIN.
Note that this query will give the same result as solution 2 when there are duplicate values. If you want to have also only one result like with solution 1, it suffices to add TOP 1 after SELECT.
Here is a fiddle.
Alternative with pure INNER JOIN
If you really want an INNER join, then this will do it. Again the TOP 1 is only needed if you have non-unique values:
SELECT TOP 1 t1.name
FROM test t1
INNER JOIN (SELECT Max(value) AS value FROM test) t2
ON t2.value = t1.value;
But this one really is very similar to what you did in solution 2. Here is fiddle for it.

SQL join format - nested inner joins

I have the following SQL statement in a legacy system I'm refactoring. It is an abbreviated view for the purposes of this question, just returning count(*) for the time being.
SELECT COUNT(*)
FROM Table1
INNER JOIN Table2
INNER JOIN Table3 ON Table2.Key = Table3.Key AND Table2.Key2 = Table3.Key2
ON Table1.DifferentKey = Table3.DifferentKey
It is generating a very large number of records and killing the system, but could someone please explain the syntax? And can this be expressed in any other way?
Table1 contains 419 rows
Table2 contains 3374 rows
Table3 contains 28182 rows
EDIT:
Suggested reformat
SELECT COUNT(*)
FROM Table1
INNER JOIN Table3
ON Table1.DifferentKey = Table3.DifferentKey
INNER JOIN Table2
ON Table2.Key = Table3.Key AND Table2.Key2 = Table3.Key2
For readability, I restructured the query... starting with the apparent top-most level being Table1, which then ties to Table3, and then table3 ties to table2. Much easier to follow if you follow the chain of relationships.
Now, to answer your question. You are getting a large count as the result of a Cartesian product. For each record in Table1 that matches in Table3 you will have X * Y. Then, for each match between table3 and Table2 will have the same impact... Y * Z... So your result for just one possible ID in table 1 can have X * Y * Z records.
This is based on not knowing how the normalization or content is for your tables... if the key is a PRIMARY key or not..
Ex:
Table 1
DiffKey Other Val
1 X
1 Y
1 Z
Table 3
DiffKey Key Key2 Tbl3 Other
1 2 6 V
1 2 6 X
1 2 6 Y
1 2 6 Z
Table 2
Key Key2 Other Val
2 6 a
2 6 b
2 6 c
2 6 d
2 6 e
So, Table 1 joining to Table 3 will result (in this scenario) with 12 records (each in 1 joined with each in 3). Then, all that again times each matched record in table 2 (5 records)... total of 60 ( 3 tbl1 * 4 tbl3 * 5 tbl2 )count would be returned.
So, now, take that and expand based on your 1000's of records and you see how a messed-up structure could choke a cow (so-to-speak) and kill performance.
SELECT
COUNT(*)
FROM
Table1
INNER JOIN Table3
ON Table1.DifferentKey = Table3.DifferentKey
INNER JOIN Table2
ON Table3.Key =Table2.Key
AND Table3.Key2 = Table2.Key2
Since you've already received help on the query, I'll take a poke at your syntax question:
The first query employs some lesser-known ANSI SQL syntax which allows you to nest joins between the join and on clauses. This allows you to scope/tier your joins and probably opens up a host of other evil, arcane things.
Now, while a nested join cannot refer any higher in the join hierarchy than its immediate parent, joins above it or outside of its branch can refer to it... which is precisely what this ugly little guy is doing:
select
count(*)
from Table1 as t1
join Table2 as t2
join Table3 as t3
on t2.Key = t3.Key -- join #1
and t2.Key2 = t3.Key2
on t1.DifferentKey = t3.DifferentKey -- join #2
This looks a little confusing because join #2 is joining t1 to t2 without specifically referencing t2... however, it references t2 indirectly via t3 -as t3 is joined to t2 in join #1. While that may work, you may find the following a bit more (visually) linear and appealing:
select
count(*)
from Table1 as t1
join Table3 as t3
join Table2 as t2
on t2.Key = t3.Key -- join #1
and t2.Key2 = t3.Key2
on t1.DifferentKey = t3.DifferentKey -- join #2
Personally, I've found that nesting in this fashion keeps my statements tidy by outlining each tier of the relationship hierarchy. As a side note, you don't need to specify inner. join is implicitly inner unless explicitly marked otherwise.