我似乎在提出查询以实现我想要的方面遇到了一些麻烦。我有一张如下表:
| Date(TIMESTAMP) | Count |
|---------------------|-------|
| 2016-02-01 01:00:00 | 52 |
| 2016-01-05 11:30:00 | 14 |
| 2016-02-01 04:20:00 | 36 |
| ... | ... |
该表有大约40,000行。我想要做的是获取多个日期范围的总数,所以我最终得到以下内容......
| Period | Total |
|------------|-------|
| All | 10245 |
| Past year | 1401 |
| Past month | 104 |
| Past week | 26 |
目前,我在PHP脚本中运行循环,并为我正在寻找的每个日期范围执行单独查询。实际上我在循环中有大约10个查询来获取不同的统计数据但是对于这个例子我正在简化它。这需要永远,我希望有一个更优雅的方式来做到这一点,但我花了相当多的时间现在尝试不同的东西和研究,并没有取得任何进展。我理解如何使用CASE进行分组,但不知道何时记录可能需要在多个分箱中。有什么帮助吗?
答案 0 :(得分:0)
试试这个UNION
查询:
SELECT 'All', COUNT(*) AS Total FROM yourTable
UNION
SELECT 'Past year', COUNT(*) AS Total
FROM yourTable
WHERE DATE(TIMESTAMP) > DATE_ADD(NOW(), INTERVAL -1 YEAR)
UNION
SELECT 'Past month', COUNT(*) AS Total
FROM yourTable
WHERE DATE(TIMESTAMP) > DATE_ADD(NOW(), INTERVAL -1 MONTH)
UNION
SELECT 'Past week', COUNT(*) AS Total
FROM yourTable
WHERE DATE(TIMESTAMP) > DATE_ADD(NOW(), INTERVAL -1 WEEK)
答案 1 :(得分:0)
第一。知道函数获取年份的第一个日期,月份的第一个日期和星期的第一个日期。 然后使用count和filter编写你的sql,其中包含不同时期的第一个和最后一个日期。
REF:
MySQL Select First Day of Year and Month
月 https://stackoverflow.com/a/19259159/1258492
周https://stackoverflow.com/a/11831133/1258492
select 'All' as period, count(1) from
tbl
union
select 'Past Year' as period, count(1) from
tbl
where timestamp between
MAKEDATE(year(now())-1,1) and
last_day(MAKEDATE(year(now())-1,1) + interval 11 month)
union
select 'Past Month' as period, count(1) from
tbl
where timestamp between
LAST_DAY(NOW() - INTERVAL 2 MONTH) + INTERVAL 1 DAY and
LAST_DAY(NOW() - INTERVAL 1 MONTH)
union
select 'Past Week' as period, count(1) from
tbl
where timestamp between
adddate(curdate(), INTERVAL 1-DAYOFWEEK(curdate())-7 DAY) and
adddate(curdate(), INTERVAL 7-DAYOFWEEK(curdate())-7 DAY) ;
答案 2 :(得分:0)
您可以使用子查询。每次细分使用一个子查询,如下所示:
SELECT everything, 'past year'
FROM
(
SELECT sum(c) AS 'everything'
FROM reports
) t1,
(
SELECT sum(c) AS 'past year'
FROM reports
WHERE d >= DATE_ADD(CURDATE(), INTERVAL -1 YEAR)
) t2