如何转换此结果:
week,day,hour,branch,sales
1,1,1,a,50
1,1,1,b,50
1,1,2,a,25
1,1,2,b,75
进入这个:
week,day,hour,branch,sales,percentage
1,1,1,a,50,50%
1,1,1,b,50,50%
1,1,2,a,25,25%
1,1,2,b,75,75%
请注意,百分比按每小时分组。换句话说,它不是所有销售的百分比,而只是每小时内的销售额。我尝试了以下查询,但这给了我所有销售的百分比:
SELECT week,day,hour,branch,sales,
(sales/(SELECT SUM(sales) FROM test))*100 AS Percentage
FROM test
GROUP BY week,day,hour,branch
答案 0 :(得分:1)
使用相关子查询:
SELECT week, day, hour, branch, sales,
(sales/(SELECT SUM(sales)
FROM test t2
WHERE t2.hour = t.hour and t2.week = t.week and t2.day = t.day
)
) * 100 AS Percentage
FROM test t
GROUP BY week, day, hour, branch;