这是为了计算最后一天有多少人访问过。我还想包括在过去一周和一年中有多少人访问并完全输出它而不进行3次单独的查询。
SELECT COUNT(updated_at) AS 'TODAY'
FROM parts_development.page_views p
WHERE updated_at >= DATE_SUB(NOW(),INTERVAL 1 day)
GROUP BY parts_user_id;
答案 0 :(得分:3)
SELECT DAY(updated_at), WEEK(updated_at), COUNT(*) AS visits
FROM parts_development.page_views p
WHERE updated_at >= DATE_SUB(NOW(),INTERVAL 1 year)
GROUP BY
DAY(updated_at), WEEK(updated_at) WITH ROLLUP
这将计算一年内的访问次数,按天,周和总计对其进行分组。
如果您只想在三列中选择一天,一周和一年的访问次数,请使用以下命令:
SELECT (
SELECT COUNT(*)
FROM parts_development.page_views p
WHERE updated_at >= DATE_SUB(NOW(),INTERVAL 1 DAY)
) AS last_day,
(
SELECT COUNT(*)
FROM parts_development.page_views p
WHERE updated_at >= DATE_SUB(NOW(),INTERVAL 7 DAY)
) AS last_week,
(
SELECT COUNT(*)
FROM parts_development.page_views p
WHERE updated_at >= DATE_SUB(NOW(),INTERVAL 1 YEAR)
) AS last_year
答案 1 :(得分:2)
SQL UNION运算符 http://www.w3schools.com/sql/sql_union.asp
答案 2 :(得分:1)
如果您还想要两行,请使用UNION ALL。你仍然有3个查询但是作为一个执行。
如果您还想要两列,请使用SUM(CASE(...))。基本上你对CASE子句的WHERE子句多3次,每个子句都有自己的条件。
答案 3 :(得分:1)
无需多次加入或从表中进行选择。
SELECT parts_user_id,
SUM( IF( updated_at >= DATE_SUB( NOW(), INTERVAL 1 DAY ), 1, 0 ) )
as day_visits,
SUM( IF( updated_at >= DATE_SUB( NOW(), INTERVAL 7 DAY ), 1, 0 ) )
as week_visits,
count(*) as year_visits
FROM parts_development.page_views
WHERE updated_at >= DATE_SUB( NOW(),INTERVAL 1 year )
GROUP BY parts_user_id
答案 4 :(得分:0)
SELECT COUNT(updated_at) AS 'TODAY'
FROM parts_development.page_views day
INNER JOIN (SELECT COUNT(updated_at) AS 'WEEK', parts_user_id as userid
FROM parts_development.page_views p
WHERE updated_at >= DATE_SUB(NOW(),INTERVAL 1 week)
GROUP BY parts_user_id) week
ON day.parts_user_id = week.userid
INNER JOIN (SELECT COUNT(updated_at) AS 'YEAR', parts_user_id as userweek
FROM parts_development.page_views p
WHERE updated_at >= DATE_SUB(NOW(),INTERVAL 1 year)
GROUP BY parts_user_id) year
ON day.parts_user_id = year.userid
WHERE day.updated_at >= DATE_SUB(NOW(),INTERVAL 1 day)
GROUP BY day.parts_user_id
不要引用我的“INTERVAL”语法,我没有查找,我自己就是TSQL人。这也可以通过工会来完成。您还可以使用连接中的谓词替换where子句。
答案 5 :(得分:0)
怎么样
SELECT count(*), IsToday(), IsThisWeek()
FROM whatever
WHERE IsThisYear()
GROUP BY IsToday(), IsThisWeek()
其中Is *()函数是布尔函数(或表达式)