我试图获取谷歌图表的数据。我想得到每天每小时的总和值。但DISTINCT
不适用于GROUP BY
。
SELECT DATE_FORMAT(created_at, "%Y-%m-%d %H:00:00") as date,
COUNT(DISTINCT visitor_id) as visitors FROM `visitors`
WHERE web='example.com' AND created_at BETWEEN '2017-11-02 00:00:00' AND '2017-11-02 23:59:59'
没有GROUP BY
的结果将是。
date visitors
---------------------|----------|
2017-11-02 14:00:00 | 2168 |
GROUP BY date
的结果将是
date visitors
---------------------|----------|
2017-11-02 00:00:00 | 19 |
2017-11-02 01:00:00 | 16 |
2017-11-02 02:00:00 | 18 |
... ...
total will be 2749
我希望达到第二个结果,但是具有唯一值的正确总和
第二个问题是我怎样才能确定几天后我的独特价值不会被分配到另一个日期?
答案 0 :(得分:2)
你应该能够用这个计算正确的总和:
SELECT DATE_FORMAT(created_at, "%Y-%m-%d %H:00:00") as date,
COUNT(visitor_id) as visitors
FROM (
SELECT MIN(created_at) AS created_at, visitor_id
FROM `visitors`
WHERE web='example.com'
AND created_at BETWEEN '2017-11-02 00:00:00' AND '2017-11-02 23:59:59'
GROUP BY visitor_id
) all_visits
GROUP BY DATE_FORMAT(created_at, "%Y-%m-%d %H:00:00")