我有一个让我感到愚蠢的问题! 我必须对我的应用程序的使用做一些统计。
我有一个表调用:customer_point
id int(11) auto_increment
id_customer int(11)
type_point int(11)
date timestamp CURRENT_TIMESTAMP
我想在整个月内提出这个请求(每晚都有一行;)):
SELECT COUNT( id_customer ) , type_point, date(date)
FROM customer_point
WHERE date BETWEEN "2014-06-01 20:00:00" AND "2014-06-02 10:00:00"
GROUP BY type_point, date;
我几乎可以肯定我错过了一个重点,但我找不到女巫。
非常感谢您阅读我! 再见,
编辑:
示例:
INSERT INTO `customer_point` ( `id` , `id_customer` , `type_point`, `date` )
VALUES ( '', '15', '1', '2014-06-01 22:50:00'), ( '', '15', '1', '2014-06-01 23:52:00'), ( '', '15', '1', '2014-06-02 9:50:00'), ( '', '15', '1', '2014-06-30 22:50:00'), ( '', '15', '1', '2014-06-30 23:52:00'), ( '', '15', '1', '2014-07-01 02:50:00', ( '', '15', '1', '2014-07-01 09:50:00');
结果:
1, 3, 2014-06-01
1, 4, 2014-06-30
我希望这有助于理解我的问题:/
答案 0 :(得分:1)
如果您只是想要实际数据的coutns,请检查日期是否在您感兴趣的范围内,并且时间是在晚上(即,大于晚上8点或小于上午10点,如果您的SQL看起来如此): -
SELECT type_point, date(customer_point.date) AS aDate, COUNT( id_customer )
FROM customer_point
WHERE DATE(customer_point.date) BETWEEN "2014-06-01" AND "2014-06-30"
AND TIME(customer_point.date) >= '20:00:00' OR TIME(customer_point.date) <= '10:00:00'
GROUP BY type_point, aDate;
要获得每天一行,无论当天是否有任何数据(即,数量为零,没有数据),您需要生成日期列表,然后将数据LEFT JOIN加入。
这样的事情: -
SELECT sub0.aDate, type_point, COUNT( id_customer )
FROM
(
SELECT DATE_ADD('2014-06-01', INTERVAL units.i + tens.i * 10 DAY) AS aDate
FROM
(SELECT 0 i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) units
CROSS JOIN
(SELECT 0 i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3) tens
) sub0
LEFT OUTER JOIN customer_point
ON sub0.aDate = date(customer_point.date)
WHERE sub0.aDate BETWEEN "2014-06-01" AND "2014-06-30"
GROUP BY sub0.aDate, type_point;
您可能还需要生成type_point值列表。
编辑 - 要更新问题,您可以从日期/时间中减去10个小时。所以7月1日上午10点到6月30日午夜?
SELECT type_point, date(DATE_ADD(customer_point.date, INTERVAL -10 HOUR)) AS aDate, COUNT( id_customer )
FROM customer_point
WHERE DATE(DATE_ADD(customer_point.date, INTERVAL -10 HOUR)) BETWEEN "2014-06-01" AND "2014-06-30"
AND TIME(customer_point.date) >= '20:00:00' OR TIME(customer_point.date) <= '10:00:00'
GROUP BY type_point, aDate;
SQL小提琴: -
http://www.sqlfiddle.com/#!2/ddc95/2
问题在于,6月1日上午10点之前的物品是否计入5月或6月的日期?
答案 1 :(得分:0)
使用mysql你甚至可以做到
WHERE date LIKE "2014-06-%"
编辑:您需要从20:00开始,然后您必须考虑下一个mounth的第一天,直到22:00 ......
好的,然后将这20个小时减去日期:
SELECT DATE_SUB(column, INTERVAL 20 HOUR)....
最后:
SELECT COUNT( id_customer ) , type_point, DATE_SUB(date, INTERVAL 20 HOUR) as mydate
FROM customer_point
WHERE mydate LIKE "2014-06-%"
GROUP BY type_point, date;