我有一个包含一些列的表,其中一个包含我用来运行的时间戳
目前有四个单一选择来计算SELECT count()
并返回信息
比如“超过1周的n行”,“超过2周的n行”,......
如何将四个查询转换为一个有希望的SQL语句 跑得更快?
陈述如下:
SELECT count(foo_pk) AS oneweek FROM foo WHERE foo_timstamp < DATE_SUB(now(), INTERVAL 1 week)
答案 0 :(得分:5)
我不是MySql人,但在SQL Server中我会像这样使用CASE语句:
SELECT
SUM(CASE WHEN foo_timstamp < DATE_SUB(now(), INTERVAL 1 week) THEN 1 ELSE 0 END) as oneweek,
SUM(CASE WHEN foo_timstamp < DATE_SUB(now(), INTERVAL 2 week) THEN 1 ELSE 0 END) as twoweek,
SUM(CASE WHEN foo_timstamp < DATE_SUB(now(), INTERVAL 3 week) THEN 1 ELSE 0 END) as threeweek,
SUM(CASE WHEN foo_timstamp < DATE_SUB(now(), INTERVAL 4 week) THEN 1 ELSE 0 END) as fourweek
FROM foo
WHERE
foo_timstamp < DATE_SUB(now(), INTERVAL 1 week)
似乎这个语句也可以在MySql中使用,所以虽然我的语法可能有些偏差,但我认为像上面的SQL这样的东西应该有效。
答案 1 :(得分:5)
SELECT
COUNT(1) AS olderthanoneweek,
COUNT(CASE WHEN foo_timstamp < DATE_SUB(now(), INTERVAL 2 week) THEN 1 END) AS olderthantwoweek,
COUNT(CASE WHEN foo_timstamp < DATE_SUB(now(), INTERVAL 3 week) THEN 1 END) AS olderthanthreeweek,
COUNT(CASE WHEN foo_timstamp < DATE_SUB(now(), INTERVAL 4 week) THEN 1 END) AS olderthanfourweek
FROM foo
WHERE foo_timstamp < DATE_SUB(now(), INTERVAL 1 week)
答案 2 :(得分:0)
未尝试,但是..
select count(foo_pk),
if(foo_timestamp<date_sub(now(),interval 1 week,"in the last week",
if(foo_timestamp<date_sub(now(),interval 2 week,"in the last 2 weeks",
if(foo_timestamp<date_sub(now(),interval 3 week,"in the last 3 weeks",
if(foo_timestamp<date_sub(now(),interval 4 week,"in the last 4 weeks",
"4 weeks or more ")))) as foo_label
order by foo_label
group by foo_label;
答案 3 :(得分:0)
如果您愿意,可以使用这样的行:
SELECT DATE_SUB(now(), INTERVAL) AS WEEK_DIFF,
count(foo_pk) AS COUNT_PER_WEEK
FROM foo
GROUP BY DATE_SUB(now(), INTERVAL);
答案 4 :(得分:0)
select count(*),
round(datediff(curdate(), foo_pk) / 7)
as week_diff
from wolffinder_experiment
group by week_diff
order by week_diff
having week_diff <= 4
limit 4;