我的SQL有问题。我创建了这个查询:
我不知道如何通过一个查询获得该结果。我知道要计算百分比,我必须将计数器中获得的值乘以100并除以整个计数的总和。你能救我吗?
非常感谢。
答案 0 :(得分:0)
我认为最简单的方法是使用变量:
SELECT browser, counter, counter / @sum
FROM (SELECT browser, count(*) as counter, (@sum := @sum + count(*))
FROM analyticsCbVisits v INNER JOIN
analyticsCbPlatformsBrowsers pb
ON v.idChatBotTrackOperation = pb.idChatBotTrackOperation INNER JOIN
analyticsBrowsers b
ON pb.browser_id = b.id CROSS JOIN
(SELECT @sum := 0) params
WHERE b.idChatBotTrackOperation = 33
GROUP BY browser
) x
在其他数据库中,这更简单,因为您可以使用窗口函数。
答案 1 :(得分:0)
试试这个:
set @csum := 0;
SELECT browser,counter,CONCAT(FORMAT(IF(total=0,0,(counter*100.0)/total),2),'%') as percentage FROM(
SELECT browser, count(*) as counter,@csum := @csum+count(*) as total
FROM analyticsCbVisits
INNER JOIN analyticsCbPlatformsBrowsers ON analyticsCbVisits.idChatBotTrackOperation = analyticsCbPlatformsBrowsers.idChatBotTrackOperation
INNER JOIN analyticsBrowsers ON analyticsCbPlatformsBrowsers.browser_id = analyticsBrowsers.id
WHERE analyticsCbVisits.idChatBotTrackOperation = 33
GROUP BY browser) t
另一种解决方法:
SELECT browser,counter,CONCAT(FORMAT(IF(total=0,0,(counter*100.0)/total),2),'%') as percentage FROM(
SELECT browser, count(*) as counter,(SELECT count(*)
FROM analyticsCbVisits
INNER JOIN analyticsCbPlatformsBrowsers ON analyticsCbVisits.idChatBotTrackOperation = analyticsCbPlatformsBrowsers.idChatBotTrackOperation
INNER JOIN analyticsBrowsers ON analyticsCbPlatformsBrowsers.browser_id = analyticsBrowsers.id
WHERE analyticsCbVisits.idChatBotTrackOperation = 33) as total
FROM analyticsCbVisits
INNER JOIN analyticsCbPlatformsBrowsers ON analyticsCbVisits.idChatBotTrackOperation = analyticsCbPlatformsBrowsers.idChatBotTrackOperation
INNER JOIN analyticsBrowsers ON analyticsCbPlatformsBrowsers.browser_id = analyticsBrowsers.id
WHERE analyticsCbVisits.idChatBotTrackOperation = 33
GROUP BY browser) t
答案 2 :(得分:0)
SELECT Table1.Browser, Table1.Counter, Round((Table1.Counter/(Select sum(Table1.Counter) from Table1))*100,2) & " %" AS Percentage
FROM Table1;
此查询在Access中完美运行。它也应该在SQL中。试一试
答案 3 :(得分:0)
我会使用WITH ROLLUP
来获取总计数
| Browser | Counter |
---------------------
| Firefox | 2 |
| Chrome | 1 |
| NULL | 3 |
并计算申请方的百分比。
但是 - 如果您只想运行查询并导出结果,可以将总计数保存到子查询中的会话变量中,并在外部选择中使用它:
SELECT browser, counter, 100 * counter / @total as percentage
FROM (
SELECT browser,
CASE WHEN browser IS NULL
THEN @total := COUNT(*)
ELSE COUNT(*)
END AS counter
FROM analyticsCbVisits
INNER JOIN analyticsCbPlatformsBrowsers ON analyticsCbVisits.idChatBotTrackOperation = analyticsCbPlatformsBrowsers.idChatBotTrackOperation
INNER JOIN analyticsBrowsers ON analyticsCbPlatformsBrowsers.browser_id = analyticsBrowsers.id
WHERE analyticsCbVisits.idChatBotTrackOperation = 33
GROUP BY browser
) t
WHERE browser IS NOT NULL
以下是简化演示:http://rextester.com/QAT75385