[英]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. 详细地说,如果我在每个月和12个月中有100名员工,则希望获得一个包含120,000行(每月100 * 100个笛卡尔数)的输出表,乘以12(每月1个),而不是做一个完整的笛卡尔数将是1,440,000。
Yes, it is called an inner join
: 是的,它称为
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: 您可以使用
where
和cross join
来表达相同的东西,但是我认为inner join
比:
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. 请注意,您正在使用
select *
,这意味着您将拥有重复的列名,并且不知道它们来自哪个t1
。 If that is an issue, ask another question. 如果这是一个问题,请问另一个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.