我存储命中。我的表看起来像这样:
ID | time | Country
--------------------------------
1 | 01:00:00 | France
2 | 01:00:00 | Brazil
3 | 01:00:00 | USA
4 | 02:00:00 | USA
这是我的疑问:
SELECT COUNT(*) as total_hits, HOUR(time) as hour, Country
FROM hits
WHERE time >= CURDATE()
GROUP BY HOUR(time)
它确实计算了我得到的点击次数并按小时分组:
01:00:00
Total hits: 3
02:00:00
Total hits: 1
但这就是我的需要:
01:00:00
Total hits: 3
02:00:00
Total hits: 1
-----------
France: 1
USA: 2
Brazil: 1
我知道我能做到:
SELECT
COUNT(*)
, HOUR(time)
, COUNT(IF( Country = 'France', Country, null)) AS France
, COUNT(IF( Country = 'USA', Country, null)) AS USA
, COUNT(IF( Country = 'Brazil', Country, null)) AS Brazil
FROM hits
WHERE time >= CURDATE()
GROUP BY HOUR(time)
或者使用CASE
或SUM(Country = 'France') AS France
。
但在国家专栏中,不仅仅有3个国家。如果我对每个国家都这样做,我的查询会很长。
修改
我可以像Alex Monthy一样回答:
SELECT COUNT(*), Country, HOUR(time)
FROM hits
WHERE time >= CURDATE()
GROUP BY Country, HOUR(time)
但是输出将是这样的:
01:00:00
Total hits: 1
Country: France
01:00:00
Total hits: 1
Country: Brazil
01:00:00
Total hits: 1
Country: USA
02:00:00
Total hits: 1
Country: USA
但是我需要一个如上所述的输出。
TL; DR :我想要一个按时间分组的结果,另一个按国家分组。
答案 0 :(得分:1)
正如你自己说的那样:
我需要按时间(小时)和国家/地区分组
就这样做:
SELECT COUNT(*), Country, HOUR(time)
FROM hits
WHERE time >= CURDATE()
GROUP BY Country, HOUR(time)
答案 1 :(得分:1)
可能需要使用交叉连接来获取每个国家/小时的计数的子查询,然后将其连接到点击以获得总计数,使用GROUP_CONCAT来提供该小时的国家/地区计数
这样的事情: -
SELECT hour(hits.time), COUNT(DISTINCT hits.id), GROUP_CONCAT(DISTINCT CONCAT_WS(' - ', sub0.Country, sub0.country_count))
FROM hits
INNER JOIN
(
SELECT hour(hits.time) as the_hour, Country, COUNT(*) AS country_count
FROM hits
GROUP BY the_hour, Country
) sub0
ON hour(hits.time) = sub0.the_hour
GROUP BY the_hour
答案 2 :(得分:0)
真的不确定,但你试过吗
SELECT COUNT(*), HOUR(time)
FROM hits
WHERE time >= CURDATE()
GROUP BY Country
答案 3 :(得分:0)
SELECT COUNT(*) AS `totals`, country, HOUR(time) AS `hour`
FROM hits
WHERE time >= CURDATE()
GROUP BY country, HOUR(time) WITH ROLLUP;
这不仅可以按国家/地区和小时为您提供分组,还可以为具有总计的国家/地区提供小计。
http://dev.mysql.com/doc/refman/5.7/en/group-by-modifiers.html
答案 4 :(得分:0)
试试这个
SELECT
DISTINCT Country,
COUNT(HOUR (time))
FROM
hits
WHERE
time >= CURDATE()
GROUP BY country