2017-08-08 30 views
1

我想写一个查询,其中我计算了一个文件已被查看的次数和它已被下载的次数在每个用户的基础上。mysql查询计数的用户和文件名基于不同的列值

Dataset 
Userid | callaction | description 
1  | Viewed  | abc.pdf 
2  | Viewed  | abc.pdf 
2  | Viewed  | xyz.pdf 
1  | Viewed  | abc.pdf 
1  | Downloaded | abc.pdf 
1  | Downloaded | abc.pdf 
1  | Downloaded | abc.pdf 
2  | Downloaded | xyz.pdf 
1  | Downloaded | xyz.pdf 

我的查询是:

select userid, description, 
count(description) as 'Number of views', 
count(description) as 'Number of Downloads' 
from tablename 
where callaction = 'VIEWFILE' OR callaction = 'DOWNLOAD' 
group by userid, description; 

但是,这是给我在看一个表,下载是这是错误的一样

我找的结果是:

Userid | callaction | description | Number of views | Number of Downloads 
1  | Viewed  | abc.pdf  | 2    | 3 
1  | Viewed  | xyz.pdf  | 0    | 1 
2  | Viewed  | abc.pdf  | 1    | 0 
2  | Viewed  | xyz.pdf  | 1    | 1 

回答

4
select userid, description, 
     sum(callaction = 'VIEWFILE') as 'Number of views', 
     sum(callaction = 'DOWNLOAD') as 'Number of Downloads' 
from tablename 
group by userid, description; 
+0

感谢百万Juergen,那工作perfe ctly – stephenad