Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server - Cross join with where / on condition

I have a table with monthly data for employees that I'd like to do cross joins but only after making sure they're in the same month. Table looks like this:

  Month      Emp_id
1/1/2017      123
1/1/2017      234
1/1/2017      345
1/1/2017      456
2/1/2017      123
2/1/2017      234
2/1/2017      345
  ...

I'd like to do something like this:

select *
from t1
cross join t1 as t2
   on t1.Month = t2.Month

Is there a way to do this?

EDIT:

To elaborate, if I have 100 employees in each month and 12 months I'm looking to get an output table with 120,000 rows (100 * 100 Cartesian for each month, times 12 (1 for each month) instead of doing a full Cartesian which would be 1,440,000.

like image 455
screechOwl Avatar asked Mar 29 '18 13:03

screechOwl


People also ask

Can we use WHERE condition in cross join?

A CROSS JOIN is a JOIN operation that produces the Cartesian product of two tables. Unlike other JOIN operators, it does not let you specify a join clause. You may, however, specify a WHERE clause in the SELECT statement.

Can I use join after WHERE clause?

You join two tables by creating a relationship in the WHERE clause between at least one column from one table and at least one column from another. The join creates a temporary composite table where each pair of rows (one from each table) that satisfies the join condition is linked to form a single row.

Should I put condition in join or WHERE clause?

It is better to add the condition in the Join. Performance is more important than readability. For large datasets, it matters.

Which is executed first join or WHERE?

Save this answer. Show activity on this post. The rows selected by a query are filtered first by the FROM clause join conditions, then the WHERE clause search conditions, and then the HAVING clause search conditions. Inner joins can be specified in either the FROM or WHERE clause without affecting the final result.


1 Answers

Yes, it is called an inner join:

select *
from t1 inner join
     t1 t2
     on t1.Month = t2.Month

You could express the same thing using where and cross join, but I think an inner join is better than:

select *
from t1 cross join
     t1 t2
where t1.Month = t2.Month;

Note that you are using select *, which means that you will have duplicate column names and not know which t1 they are coming from. If that is an issue, ask another question.

like image 166
Gordon Linoff Avatar answered Oct 25 '22 04:10

Gordon Linoff