通过连接多个表来扁平化 SQL 服务器中的数据

Flattening data in SQL server by joining multiple tables

为了数据分析的目的,我想将父子 table 扁平化。 我有服务订单 table tssoc210 as

orno|acln
1   |10 
1   |20
2   |20
.
.

它的活动(劳动力,material,其他)在其他 3 个 table 中维护为 tssoc220 (劳工)

orno|acln|lino|invn|eqan|asto
1   |10  |A   |600 |2   |120
1   |10  |B   |607 |1   |100
.
.

tssoc230(materials)

orno|acln|lino|invn|eqan|asto
1   |10  |L1  |700 |1   |110
1   |10  |L2  |704 |3   |200
1   |10  |L3  |407 |4   |100
1   |20  |L1  |708 |1   |100  
2   |20  |L1  |790 |1   |200
.
.

tssoc240(其他)

orno|acln|lino|invn|eqan|asto
1   |10  |M1  |400 |2   |500
2   |20  |M1  |490 |1   |100
.
.

我想以

的身份加入这些table
orno|acln|l_lino|l_invn|l_eqan|l_asto|m_lino|m_invn|m_eqan|m_asto|o_lino|o_invn|o_eqan|o_asto
1   |10  |A     |600   |2     |120   |NULL  |NULL  |NULL  |NULL  |NULL  |NULL  |NULL  |NULL
1   |10  |B     |607   |1     |100   |NULL  |NULL  |NULL  |NULL  |NULL  |NULL  |NULL  |NULL
1   |10  | NULL |NULL  |NULL  |NULL  |L1    |700   |1     |110   |NULL  |NULL  |NULL  |NULL
1   |10  | NULL |NULL  |NULL  |NULL  |L2    |704   |3     |200   |NULL  |NULL  |NULL  |NULL
1   |10  | NULL |NULL  |NULL  |NULL  |L3    |407   |4     |100   |NULL  |NULL  |NULL  |NULL
1   |10  | NULL |NULL  |NULL  |NULL  |NULL  |NULL  |NULL  |NULL  |M1    |400   |2     |500
1   |20  | NULL |NULL  |NULL  |NULL  |L1    |708   |1     |100   |NULL  |NULL  |NULL  |NULL
2   |20  | NULL |NULL  |NULL  |NULL  |L1    |790   |1     |200   |NULL  |NULL  |NULL  |NULL
2   |20  | NULL |NULL  |NULL  |NULL  |NULL  |NULL  |NULL  |NULL  |M1    |490   |1     |100
.
.

如果我将 tssoc220、tssoc230、tssoc240 与 tssoc210 左连接(tssoc210 作为左 table),它会复制该行。

left join tssoc220 ON  tssoc210.orno = tssoc220.orno and tssoc210.acln = tssoc220.acln
left join tssoc230 ON  tssoc210.orno = tssoc230.orno and tssoc210.acln = tssoc230.acln 
left join tssoc240 ON  tssoc210.orno = tssoc240.orno and tssoc210.acln = tssoc240.acln 

我哪里错了?

您将需要编写 3 个只连接 1 个 table 的查询并合并它们。

SELECT tssoc210.orno,tssoc210.acln,tssoc220.l_lino,tssoc220.l_invn,tssoc220.l_eqan,tssoc220.l_asto,NULL as m_lino,NULL as m_invn,NULL as m_eqan,NULL as m_asto,NULL as o_lino,NULL as o_invn,NULL as o_eqan,NULL as o_asto
FROM tssoc210 
left join tssoc220 ON  tssoc210.orno = tssoc220.orno and tssoc210.acln = tssoc220.acln
UNION ALL 
SELECT  tssoc210.orno,tssoc210.acln,NULL as l_lino,NULL as l_invn,NULL as l_eqan,NULL as l_asto,tssoc230.m_lino,tssoc230.m_invn,tssoc230.m_eqan,tssoc230.m_asto,NULL as o_lino,NULL as o_invn,NULL as o_eqan,NULL as o_asto
FROM tssoc210 
left join tssoc230 ON  tssoc210.orno = tssoc230.orno and tssoc210.acln = tssoc230.acln 
UNION ALL 
SELECT  tssoc210.orno,tssoc210.acln,NULL as l_lino,NULL as l_invn,NULL as l_eqan,NULL as l_asto,,NULL as m_lino,NULL as m_invn,NULL as m_eqan,NULL as m_asto,tssoc240.o_lino,tssoc240.o_invn,tssoc240.o_eqan,tssoc240.o_asto
FROM tssoc210 
left join tssoc240 ON  tssoc210.orno = tssoc240.orno and tssoc210.acln = tssoc240.acln