我有一个查询,该查询返回每天与给定搜索词匹配的日志消息数。
SELECT
DATE_FORMAT(logtime, '%d.%m.%y') AS `day`,
COUNT(DATE_FORMAT(logtime, '%d.%m.%y')) AS `total`
FROM log
WHERE message like '%searchterm%'
GROUP BY `day` ORDER BY logid DESC
我想做的是获取总数,即相同的查询但没有where子句,并显示每天的第一个总数占第二个总数的百分比。我该怎么做呢?
最佳答案
这样的事情应该可以解决问题:
select tot.day,tot.total,ifnull(s.total,0) as searchTermTotal,
round(100*ifnull(s.total,0)/tot.total,2) as percentage
from
(
SELECT DATE_FORMAT(logtime, '%d.%m.%y') AS `day`,
COUNT(DATE_FORMAT(logtime, '%d.%m.%y')) AS `total`
FROM log
GROUP BY `day`
) tot
left join
(
SELECT DATE_FORMAT(logtime, '%d.%m.%y') AS `day`,
COUNT(DATE_FORMAT(logtime, '%d.%m.%y')) AS `total`
FROM log
WHERE message like '%searchterm%'
GROUP BY `day`
) s on s.day = tot.day;
也应该选择零百分比。
关于mysql - MySQL将查询结果的子集(即两个查询)表示为百分比,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8726662/