简体   繁体   English

我的SQL查询有什么问题? (无法获得理想的输出/输出)

[英]Whats wrong with my SQL Query? (not getting desired o/p)

I want my query to return number of users registered in a particular day between current date and 7 days before. 我希望查询返回当前日期至7天之前的特定日期注册的用户数。 Instead of days, in date-time format it shows it in integer format. 它以日期时间格式(而不是日期)以整数格式显示。 Example, for date 20/12/2012 its showing as 0, 21/12/2012 as 1 and so on 例如,对于日期20/12/2012,其显示为0,在2012年12月21日显示为1,依此类推

My Query: 我的查询:

select date(update_timestamp) between date_sub(sysdate(), interval 7 day) and sysdate()  as date, count(*) users 
from registered 
group by date(update_timestamp)

Desired Output 期望的输出

DATE       | USERS
20/12/2012 | 5
21/12/2012 | 6

Output i'm getting 我得到的输出

DATE  | USERS
    0 | 5
    1 | 6

What is wrong with my sql query? 我的SQL查询有什么问题? Also, i need to know the alternate way of fetching last 7 days data 另外,我需要知道获取最近7天数据的另一种方法

I think you want a WHERE clause: 我认为您想要一个WHERE子句:

select date(update_timestamp) Date, count(*) users 
from registered 
where date(update_timestamp) between date_sub(sysdate(), interval 7 day) and sysdate()
group by date(update_timestamp)

You have put the condition in the select statement, so it will be evaluated and returned, instead of limiting the result. 您已将条件放入select语句中,因此它将被评估并返回,而不是限制结果。 Put the condition in the where statement: 将条件放在where语句中:

select date(update_timestamp) as date, count(*) users
from registered
where date(update_timestamp) between date_sub(sysdate(), interval 7 day) and sysdate()
group by date(update_timestamp)

To get all the dates in the interval even if there are no users, you need to join in another source of data: 要获得间隔中的所有日期(即使没有用户),也需要加入另一个数据源:

select date_sub(sysdate(), interval d.offset day) date, count(r.update_timestamp) users
from registered r
inner join (
  select 0 as offset union all
  select 1 union all
  select 2 union all
  select 3 union all
  select 4 union all
  select 5 union all
  select 6 union all
  select 7
) d on date(r.update_timestamp) = date_sub(sysdate(), interval d.offset day)
group by date_sub(sysdate(), interval d.offset day)

try this query :: 试试这个查询::

where clause is the filtering part, For the date type logic you should use your current day - 7 days logic in that part of the query. where子句是过滤部分,对于日期类型逻辑,应在查询的那部分使用当前日期-7天逻辑。

select date(update_timestamp) ,count(*) users 
from registered 
where date(update_timestamp) 
between 
date_sub(sysdate(), interval 7 day) and sysdate()  
group by date(update_timestamp)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM