SQL - 为select子句添加计数

时间:2012-03-08 21:39:58

标签: mysql sql

我有这个查询在我的网站上显示趋势(搜索次数最多)的名单:

SELECT name, COUNT(*) AS total_trends
FROM trending_names
WHERE dateTime BETWEEN '"&fromDate&"' AND '"&toDate&"' // -7 days to Now()
GROUP BY name
ORDER BY COUNT(*) DESC
LIMIT 10;

...这就是我打印到屏幕的结果: (数字代表搜索量)

Angelina Jolie        31,293
Rihanna               26,722
Lindsay Lohan         18,351
Brad Pitt             11,901

我现在想将数字改为百分比;所以我真的需要在过去7天内获得所有趋势名称的总数,以计算正确的百分比。

我是否可以在不添加其他查询的情况下为此查询添加总计数?

5 个答案:

答案 0 :(得分:3)

您可以在单个查询中执行:

尝试下面的内容:

SELECT name, COUNT(*) AS total_trends,
sum(if(dateTime BETWEEN '"&fromDate&"' AND '"&toDate&"' ,1,0)) as total_last_7_days,
((sum(if(dateTime BETWEEN '"&fromDate&"' AND '"&toDate&"' ,1,0)) /COUNT(*) ) *100)
as percentage                          // if you want to get only percentage
FROM trending_names
GROUP BY name
ORDER BY COUNT(*) DESC
LIMIT 10;

答案 1 :(得分:1)

您可以使用子查询:

SELECT name, ((COUNT(*)*100)/(SELECT COUNT(*) FROM trending_names))  AS total_trends
FROM trending_names
WHERE dateTime BETWEEN '"&fromDate&"' AND '"&toDate&"' // -7 days to Now()
GROUP BY name
ORDER BY COUNT(*) DESC
LIMIT 10;

答案 2 :(得分:1)

我知道你没有运行SQL Server,但有些读者可能会对这种可能的紧凑型解决方案感兴趣(SQL Server 2008或更高版本)。我不确定很多人都知道你可以有一个聚合聚合的窗口聚合。

select
  name,
  100.0*count(*)/sum(count(*)) over () as pct_trends
from trending_names
where dateTime between getdate()-7 and getdate()
group by name;

答案 3 :(得分:0)

不,我不这么认为。您需要在单独的(子)选择

上计算总计数

答案 4 :(得分:0)

SELECT name,(total_trends*100.0/sum_total_trends) pct_trends
FROM
(
    SELECT name, COUNT(*) AS total_trends 
    FROM trending_names 
    WHERE dateTime BETWEEN '"&fromDate&"' AND '"&toDate&"' // -7 days to Now() 
    GROUP BY name 
    WITH ROLLUP
) A,
(
    SELECT COUNT(*) AS sum_total_trends 
    FROM trending_names 
    WHERE dateTime BETWEEN '"&fromDate&"' AND '"&toDate&"' // -7 days to Now() 
) B;