PHP MySQL:COUNT / SUM一个具有不同值的非整数列

时间:2014-06-08 16:22:39

标签: php mysql sql select group-by

我的表格如下:

ID | click |    time    | browser

1      1      [01:00:00]     FireFox
2      1      [01:00:00]     FireFox
3      0      [01:00:00]     Opera
4      1      [02:00:00]     FireFox
5      1      [02:00:00]     Chrome
6      1      [02:00:00]     Chrome

所以输出应该是:

01:00:00
Total hits: 3
Clicks: 2
FireFox: 2
Opera: 1

02:00:00
Total hits: 3
Clicks: 3
FireFox: 1
Chrome: 2

我知道如何在没有浏览器的情况下获得此功能:

SELECT SUM(click) AS click, COUNT(*), HOUR(time) 
FROM hits 
WHERE time >= DATE_SUB(NOW(),INTERVAL 24 HOUR) GROUP BY HOUR(time)

但我不知道用浏览器输出这个。 我根本不介意浏览器不会被分组,我得到这样的输出:

01:00:00
Total hits: 3
Clicks: 2

02:00:00
Total hits: 3
Clicks: 3
-----------

FireFox: 3
Chrome: 2
Opera: 1

1 个答案:

答案 0 :(得分:1)

您可以使用IF

SELECT SUM(`click`) AS click
     , COUNT(*)
     , HOUR(`time`)
     , COUNT(IF( `browser` = 'Chrome', `browser`, null)) AS `Chrome`
     , COUNT(IF( `browser` = 'Opera', `browser`, null)) AS `Opera`
     , COUNT(IF( `browser` = 'FireFox', `browser`, null)) AS 'FireFox'
FROM `hits` 
WHERE `time` >= DATE_SUB(NOW(),INTERVAL 24 HOUR) 
GROUP BY HOUR(`time`)

CASE

SELECT SUM(`click`) AS click
     , COUNT(*)
     , HOUR(`time`)
     , COUNT(CASE WHEN `browser` = 'Chrome' THEN `browser` END) AS `Chrome`
     , COUNT(CASE WHEN `browser` = 'Opera' THEN `browser` END) AS `Opera`
     , COUNT(CASE WHEN `browser` = 'FireFox' THEN `browser` END) AS 'FireFox'
FROM `hits` 
WHERE `time` >= DATE_SUB(NOW(),INTERVAL 24 HOUR) 
GROUP BY HOUR(`time`)