我想加入两个临时表,但它会返回大量重复数据, 下面是我在加入表格之前得到的结果。
这是在我加入两个表之后,结果如下图所示
它使所有数据翻倍。
我使用这个sql加入这两个表。
` SELECT * FROM(
SELECT DISTINCT t1.hatch_num AS hatch_num_1,t1.delay_code AS delay_code_1,t1.st_time + '-' + t1.ed_time AS time_1
FROM #temp1 t1
)as a
CROSS JOIN
(
SELECT DISTINCT t2.hatch_num AS hatch_num_2,t2.delay_code AS delay_code_2,t2.st_time + '-' + t2.ed_time AS time_2
FROM #temp2 t2
)as b`
我尝试使用内连接,左连接但返回相同的结果。
这里是#temp1表sql,当我执行它时,它返回正确的数据。
SELECT DISTINCT t1.scn,CONVERT(DATE,t2.opr_st_dt_tm) as work_date,t2.hatch_num,
t3.delay_code,REPLACE(CONVERT(varchar(5),t3.delay_st_dt_tm,108),':','')[time_start],
REPLACE(CONVERT(varchar(5),t3.delay_ed_dt_tm,108),':','')[time_end]
FROM ccostallysheet t1
INNER JOIN ccostsitem t2 ON t2.master_id = t1.id
INNER JOIN ccostsdelayitem t3 ON t3.master_id = t1.id
WHERE t2.hatch_num = 'H1' AND t2.hatch_num IS NOT NULL
GROUP BY t1.scn,t2.opr_st_dt_tm,t2.hatch_num,t3.delay_code,t3.delay_st_dt_tm,t3.delay_ed_dt_tm
这里是temp2 sql
SELECT DISTINCT t1.scn,CONVERT(DATE,t2.opr_st_dt_tm)as work_date,t2.hatch_num,
t3.delay_code,REPLACE(CONVERT(varchar(5),t3.delay_st_dt_tm,108),':','')[time_start],
REPLACE(CONVERT(varchar(5),t3.delay_ed_dt_tm,108),':','')[time_end]
FROM ccostallysheet t1
INNER JOIN ccostsitem t2 ON t2.master_id = t1.id
INNER JOIN ccostsdelayitem t3 ON t3.master_id = t1.id
WHERE t2.hatch_num = 'H2' AND t2.hatch_num IS NOT NULL
GROUP BY t1.scn,t2.opr_st_dt_tm,t2.hatch_num,t3.delay_code,t3.delay_st_dt_tm,t3.delay_ed_dt_tm
如何在不创建重复结果的情况下加入两个表?
答案 0 :(得分:1)
您需要将表格加在一起。我猜延迟代码,所以像这样:
SELECT * FROM(
SELECT DISTINCT t1.hatch_num AS hatch_num_1,t1.delay_code AS delay_code_1,t1.st_time + '-' + t1.ed_time AS time_1
FROM #temp1 t1
)as a
INNER JOIN
(
SELECT DISTINCT t2.hatch_num AS hatch_num_2,t2.delay_code AS delay_code_2,t2.st_time + '-' + t2.ed_time AS time_2
FROM #temp2 t2
)as b ON a.delay_code_1 = b.delay_code_2
答案 1 :(得分:0)
CROSS JOIN
完全符合您的要求,这就是它的目的。另一方面,INNER JOIN
应该只返回一些数据,但是你并没有告诉它要返回什么,所以它就像CROSS JOIN
一样工作。 Simon向您举例说明如何告诉INNER JOIN
要返回的内容,您需要使用ON
后跟加入条件。由于您提供的信息不够充分,我不知道您的加入条件是什么,因此您必须自己解决这个问题,或者向我们提供有关您的两个表格和预期的更多详细信息。结果,所以我们可以帮助你。但是,根据您的描述,我觉得您正在寻找的内容可能是UNION
,而不是JOIN
。试试这个:
SELECT t1.hatch_num, t1.delay_code, t1.st_time + '-' + t1.ed_time AS time
FROM #temp1 t1
UNION
SELECT t2.hatch_num, t2.delay_code, t2.st_time + '-' + t2.ed_time AS time
FROM #temp2 t2
注意:您不需要在此使用DISTINCT
,因为UNION
会自动为您执行此操作。