我想按阶段计算成本,但不起作用,我的数据如下。我用这个命令来计算成本
SELECT Daily.dayno, activity.class, activity.phase,
activity.duration/sum(activity.duration)*daily.daycost as cost
from Daily INNER JOIN
(
Select activity.dailyuid, sum(activity.duration) duration
group by dailyUID
) Activity
on activity.dailyuid=daily.dailyuid
group by class, phase
显然上面的查询不起作用。我想要的是按阶段计算成本例如
阶段SS1在Dailyuid DD1中=4/12*1000,其中4是SS1的总小时数,12是Dailyuid DD1的总小时数,1000是Dailyuid DD1的成本。
另一个例子是阶段ST2=8/12*1000
IH=10.6/11.6*2000等
日报表
DailyUID | Dayno | Daycost |
---------|-------|---------|
DD1 | 1 | 1000 |
DD2 | 2 | 2000 |
DD3 | 3 | 3000 |
活动表
DailyUID | CLASS | PHASE | Duration |
-----------------------------------
DD1 | TS | SS1 | 3 |
DD1 | TS | SS1 | 1 |
DD1 | TS | ST2 | 2 |
DD1 | P | ST2 | 6 |
DD2 | P | IH1 | 6.6 |
DD2 | U | IH1 | 4 |
DD2 | TS | IH2 | 1 |
DD3 | TU | SC1 | 7 |
DD3 | P | SC2 | 8 |
DD3 | U | CMPLT | 3 |
最佳答案
如果我理解正确,您需要在加入之前预先聚合表。需要一个附加聚合:
select ap.phase,
(ap.duration / ad.duration) * d.daycost as cost
from (SELECT d.dailyUid, sum(daycost) as daycost
FROM Daily d
GROUP BY d.dailyuid
) d INNER JOIN
(Select a.dailyuid, sum(a.duration) as duration
from activity a
group by dailyUID
) ad
on ad.dailyuid = d.dailyuid join
(select a.dailyuid, a.phase, sum(a.duration) as duration
from activity a
group by a.dailyuid, a.phase
) ap
on ad.dailyuid = ap.dailyuid
group by phase;
SQL小提琴here。
关于mysql - 如何创建表格+计算成本涉及2列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34695194/