无法理解如何使用列总数乘以行的公式。
尝试了下面的代码
SELECT g.Item_No, (sum(g.units)* u.Unit_Percentage) as Units@2018Mix
FROM Global_GM_2019 g
FULL JOIN UnitMix_perc_2018 u
ON u.item_no=g.item_no
GROUP BY g.item_no;
我得到这个错误,我知道应该包括按功能分组的所有列。
Msg 8120, Level 16, State 1, Line 275
Column 'UnitMix_perc_2018.Unit_Percentage' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
预期
Products units of 2019 % of units of 2018 product mix
a 110 34 20570
b 120 23 13915
c 120 12 7260
d 130 12 7260
e 125 23 13915
已添加预期结果图片here
答案 0 :(得分:0)
尝试计算摘要表,然后进行联接(由于联接可能较小,因此运行速度可能最快)。
Select item_No, unit_sum * Unit_Percentage as Units@2018Mix
From (
SELECT item_no, sum(g.units) as unit_sum
FROM Global_GM_2019
Group by item_no
) as g
FULL JOIN UnitMix_perc_2018 u
ON u.item_no=g.item_no
或者只是将计算移到总和中
SELECT g.Item_No, sum(g.units* u.Unit_Percentage) as Units@2018Mix
FROM Global_GM_2019 g
FULL JOIN UnitMix_perc_2018 u
ON u.item_no=g.item_no
GROUP BY g.item_no;
或将单位百分比标量添加到旅游分组依据。
SELECT g.Item_No, (sum(g.units)* u.Unit_Percentage) as Units@2018Mix
FROM Global_GM_2019 g
FULL JOIN UnitMix_perc_2018 u
ON u.item_no=g.item_no
GROUP BY g.item_no, u.unit_percentage:
回复评论流... @sag,您有点作弊-您要同时提出两个问题。这两个问题是:
我已经通过三种方式回答了问题1。我只能猜测第二个问题(因为您在这个问题上没有提供任何细节)。这是我的猜测。
SELECT g.Item_No,
sum(g19.units),
(sum(g18.units)* u.Unit_Percentage) as Units@2018Mix,
/* Maybe */ (sum(g19.units) (double) / sum(g18.units) * 100.0 as g19_pcnt_increase_over_g18 /*???*/
/* I have no idea how you intend to calculate "product mix" because you provide zero information on this topic. */
FROM Global_GM_2019 g JOIN Global_gm_2018 as G18 on
g.item_id = g18.item_id
FULL JOIN UnitMix_perc_2018 u
ON u.item_no=g.item_no
GROUP BY g.item_no, u.unit_percentage:
我们只能为您提出的问题提供答案,为您提供一些支持信息。同样,请参考操作方法create a Minimal, Complete, Verifiable example。
答案 1 :(得分:0)
我怀疑您是否真的想要FULL JOIN
,因为您会得到NULL
的行。
根据您的描述,我认为您想要
SELECT g.Item_No, SUM(g.units * u.Unit_Percentage) as Units_2018Mix
FROM Global_GM_2019 g LEFT JOIN
UnitMix_perc_2018 u
ON u.item_no = g.item_no
GROUP BY g.item_no;
换句话说,在做SUM()
之前先做乘积 。