如何连接3个表MSSQL Server

时间:2016-07-14 07:28:19

标签: sql-server

在单个数据库中,我有三个表格如下:

enter image description here

我想在单个表中连接它们,有什么建议吗?

2 个答案:

答案 0 :(得分:0)

如果我正确理解你的答案你想要这样的事情:

CREATE TABLE COMBINED (/*Insert the set of fields here*/);
GO

INSERT INTO COMBINED
   SELECT  Table1.ProposalId
         , /*all other Table1 fields*/
         ,  Table2.ProposalId
         /*all other Table2 fields*/
         , Table3.ProposalId
         , /*all other Table2 fields*/
   FROM Table1
   FULL JOIN Table2
      ON Table1.ProposalId = Table2.ProposalId
   FULL JOIN Table3 
      ON Table1.ProposalId = Table3.ProposalId;

这将匹配具有相同提案ID的行(但保留其所有值为proposalid_1,proposalid_2 ......对于那些不匹配的行将为所有其他字段提供完整行和NULL其余的表格。

答案 1 :(得分:0)

感谢您的帮助,问题已经解决。

SELECT mtlreq.proposalid, mtlreq.prp_mtlreq_taskgrp,mtlreq.prp_mtlreq_taskcode,mtlreq.prp_mtlreq_itemcode,mtlreq.prp_mtlreq_rateper,mtlreq.prp_mtlreq_qty,mtlreq.prp_mtlreq_Inter_MaterCost,mtlreq.prp_mtlreq_UOM,mtlreq.item_short_desc, resreq.proposalid,resreq.prp_resreq_taskcode ,resreq.prp_resreq_resource,resreq.prp_resreq_usage,resreq.prp_resreq_uom,resreq.prp_resreq_rate,resreq.prp_resreq_overhd_pers
FROM (
   SELECT proposalid,prp_mtlreq_taskgrp,prp_mtlreq_taskcode,prp_mtlreq_itemcode,prp_mtlreq_rateper,prp_mtlreq_qty,prp_mtlreq_Inter_MaterCost,prp_mtlreq_UOM,item_short_desc,
          ROW_NUMBER() OVER (ORDER BY proposalid) AS rn
   FROM prjdet_prp_taskwork_mtlreq  ) AS mtlreq
FULL OUTER JOIN  (
   SELECT proposalid,prp_resreq_taskcode ,prp_resreq_resource,prp_resreq_usage,prp_resreq_uom,prp_resreq_rate,prp_resreq_overhd_pers,
          ROW_NUMBER() OVER (ORDER BY proposalid) AS rn
   FROM prjdet_prp_taskwork_resreq) AS resreq
ON mtlreq.rn = resreq.rn
FULL OUTER JOIN (
SELECT proposalid,mtprp_delv_lineno,mtprp_delv_itemcode,mtprp_delv_cost,mtprp_delv_linelevelmrg,mtprp_delv_proposedamt,
          ROW_NUMBER() OVER (ORDER BY proposalid) AS rn
   FROM prjproposal_delidtl ) AS delidtl
   on mtlreq.rn = delidtl.rn and resreq.rn=delidtl.rn