显示我有三个表:表1(AF),表2(MC)和表3(SC)SUM和JOIN到在一个记录
我现在有一个查询这些表为这样:
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 SeasonCost
FROM Table1 AF
FULL JOIN Table2 MC ON MC.[Product Number] = AF.[Product Number] AND MC.[Week Ending Date] = AF.[Week End Date]
FULL JOIN Table3 SC ON SC.[Product Number] = AF.[Product Number] AND SC.[Week Ending Date] = MC.[Week Ending 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'
返回以下内容:
Prod # | WE Date | IC Cost | Gross Sales | Prod Lbs | Meat Cost | Season Cost |
96443 2/4/2017 -123456 1000 2000 5000 10000
96443 2/4/2017 -123456 1000 2000 5000 20000
96443 2/4/2017 -123456 1000 2000 6000 10000
96443 2/4/2017 -123456 1000 2000 6000 20000
不过,我希望能够总结肉类和赛季表是这样的:
Prod # | WE Date | IC Cost | Gross Sales | Prod Lbs | Meat Cost | Season Cost |
96443 2/4/2017 -123456 1000 2000 11000 30000
我试过下面的语句,但我得到的所有四个记录总结为两个和这不是我想要的返回值:它返回的结果
SELECT
AF.[Product Number],
AF.[Week End Date],
AF.[Inv Change Cost],
AF.[Gross Sales Lbs],
AF.[Production Lbs],
SUM(MC.[Actual Usage Cost]) AS MeatCost,
SUM(SC.[Actual Usage Cost]) AS SeasonCost
FROM Table1 AF
JOIN Table2 MC ON MC.[Product Number] = AF.[Product Number] AND MC.[Week Ending Date] = AF.[Week End Date]
JOIN Table3 SC ON SC.[Product Number] = AF.[Product Number] AND SC.[Week Ending Date] = MC.[Week Ending 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'
GROUP BY
AF.[Product Number],
AF.[Week End Date],
AF.[Inv Change Cost],
AF.[Gross Sales Lbs],
AF.[Production Lbs];
:
Prod # | WE Date | IC Cost | Gross Sales | Prod Lbs | Meat Cost | Season Cost |
96443 2/4/2017 -123456 1000 2000 22000 60000
我是否需要总结所有的字段以获得期望的结果?
UPDATE:
我已经尝试这样的说法:
SELECT
AF.[Product Number],
AF.[Week End Date],
AF.[Inv Change Cost],
AF.[Gross Sales Lbs],
AF.[Production Lbs],
MC.MeatCost,
SC.SeasonCost
FROM Table1 AF
JOIN(
SELECT [Product Number], [Week Ending Date], SUM([Actual Usage Cost]) AS MeatCost
FROM Table2
GROUP BY [Product Number], [Week Ending Date]
)MC ON
AF.[Product Number] = MC.[Product Number] AND
AF.[Week End Date] = MC.[Week Ending Date]
JOIN(
SELECT [Product Number], [Week Ending Date], SUM([Actual Usage Cost]) AS SeasonCost
FROM Table3
GROUP BY [Product Number], [Week Ending Date]
)SC ON
SC.[Product Number] = MC.[Product Number] AND
SC.[Week Ending Date] = MC.[Week Ending Date]
WHERE
AF.[Product Number] = '96443' AND
AF.[Week End Date] = '2/4/2017';
但是,我得到了相同的结果,以前的尝试。
您是否有字段?什么是季节成本? – manderson
我有更多的领域,但其中大多数都是独特的各自的表 – jDave1984
您的查询按预期工作,但需要知道96443产品号之间的区别...表3中的某些东西。 – manderson