试图加入6个表

时间:2017-02-14 20:37:11

标签: sql-server join

我可能会尝试一些过于雄心勃勃的事情,但无论如何我都在尝试:我试图加入6个不同的牌桌。以下是SQL语句

SELECT 
AF.[Product Number], 
AF.[Week End Date], 
AF.[Inv Change Cost], 
AF.[Gross Sales Lbs], 
AF.[Production Lbs], 
ACO.CO2, 
ACO.Oil, 
MC.[Actual Usage Cost], 
SC.[Actual Usage Cost], 
AP.[Direct Lab Wkly Cst] * (1 +(AP.[Fringes Wkly Cst] / (AP.[Direct Lab Wkly Cst] + AP.[Indirect Lab Wkly Cst]))) AS DirecLaborCost, 
AP.[Indirect Lab Wkly Cst] * (1 +(AP.[Fringes Wkly Cst] / (AP.[Direct Lab Wkly Cst] + AP.[Indirect Lab Wkly Cst]))) AS IndirectLaborCost, 
AP.[Variable Wkly Cst], 
AP.[Freezing Wkly Cst], 
AP.[Packaging Wkly Cst], 
AP.[Fixed Wkly Cst], 
AP.[Non Processing Wkly Cst], 
SP.[Direct Lab Wkly Cst], 
SP.[Indirect Lab Wkly Cst], 
AP.[Fringes Wkly Cst], 
SP.[Variable Wkly Cst], 
SP.[Freezing Wkly Cst], 
SP.[Packaging Wkly Cst], 
SP.[Fixed Wkly Cst], 
SP.[Non Processing Wkly Cst] 
FROM Table1 AF 
JOIN Table2 ACO ON AF.[Product Number] = ACO.[Product Number] 
JOIN Table3 MC ON MC.[Product Number] = ACO.[Product Number] 
JOIN Table4 SC ON SC.[Product Number] = MC.[Product Number] 
JOIN Table5 AP ON AP.[Product Num] = SC.[Product Number] 
JOIN Table6 SP ON SP.[Product Num] = AP.[Product Num] 
WHERE (AF.[Week End Date] = '2/4/2017');

我目前正在收到SQL超时错误。声明太长了,还是我犯了语法错误?

编辑:

我发现由于记录数量巨大而导致我超时。我使用以下查询将查询显着缩小到16条记录:

SELECT
AF.[Product Number],
AF.[Week End Date],
AF.[Inv Change Cost],
AF.[Gross Sales Lbs],
AF.[Production Lbs],
MC.[Actual Usage Cost] AS MeatCost,
SC.[Actual Usage Cost] AS SeasoningCost,
ACO.[CO2],
ACO.[Oil],
AP.[Direct Lab Wkly Cst],
AP.[Indirect Lab Wkly Cst],
AP.[Fringes Wkly Cst],
AP.[Variable Wkly Cst],
AP.[Freezing Wkly Cst],
AP.[Packaging Wkly Cst],
AP.[Fixed Wkly Cst],
AP.[Non Processing Wkly Cst],
SP.[Direct Lab Wkly Cst],
SP.[Indirect Lab Wkly Cst],
SP.[Fringes Wkly Cst],
SP.[Variable Wkly Cst],
SP.[Freezing Wkly Cst],
SP.[Packaging Wkly Cst],
SP.[Fixed Wkly Cst],
SP.[Non Processing Wkly Cst]
FROM Table1 AF
FULL JOIN Table2 MC ON MC.[Week Ending Date] = AF.[Week End Date] AND MC.[Product Number] = AF.[Product Number]
FULL JOIN Table3 SC ON SC.[Week Ending Date] = AF.[Week End Date] AND SC.[Product Number] = AF.[Product Number]
FULL JOIN Table4 ACO ON ACO.[Product Number] = AF.[Product Number] AND ACO.[Week Ending Date] = AF.[Week End Date]
FULL JOIN Table5 AP ON AP.[Product Num] = AF.[Product Number] AND AP.[Week Ending Date] = AF.[Week End Date]
FULL JOIN Table6 SP ON SP.[Product Num] = AF.[Product Number] AND SP.[Week Ending Date] = AF.[Week End Date]
WHERE (AF.[Product Number] = '96443' AND AF.[Week End Date] = '2/4/2017' AND 
MC.[Rout Line Name] = 'Total Cost' AND SC.[Rout Line Name] = 'Total Cost')

正如我之前所述,我已将此范围缩小至16行,但我希望获得完整的1行记录

我相信正在发生的事情是MC,SC,AP和SP都返回两条记录,但我不是如何将这些值相加以将它们全部放在一行上

0 个答案:

没有答案