简体   繁体   English

使用日期和时间字符串按日期查询

[英]Querying by date with a date and time string

I have a database table where one of the columns contains date values. 我有一个数据库表,其中的一列包含日期值。 The format for the string is "YYYY-MM-DD HH24:MI:SS". 字符串的格式为“ YYYY-MM-DD HH24:MI:SS”。 I would like to be able to SELECT another column WHERE the date is XXXX/XX/XX without the time. 我希望能够在没有时间的情况下选择日期为XXXX / XX / XX的另一列。 I'm not very familiar with SQL, so I'm not exactly sure how to do this. 我对SQL不太熟悉,所以我不确定如何执行此操作。 The following code is what I'm currently trying to query with: 以下代码是我当前要查询的内容:

SELECT COUNT(DISTINCT(NETID)) EARLIEST_MONTHLY_DATE FROM REPORT_SERVICE_USAGE

WHERE EARLIEST_MONTHLY_DATE LIKE '%2014-03-14%' 

I don't know if it would be easier to truncate the time (I don't necessarily need it), but if I did, I may need some guidance on how that could be done. 我不知道截断时间是否更容易(我不一定需要),但是如果我这样做了,我可能需要一些有关如何完成时间的指导。

The most efficient way to do this is like this: 最有效的方法是这样的:

where earliest_monthly_date >= to_date('2014-03-14', 'yyyy-mm-dd')
and earliest_monthly_date < to_date('2014-03-15', 'yyyy-mm-dd')

That way you don't worry about any time portions of your date fields. 这样,您就不必担心日期字段的任何时间部分。 Here is another way, which is equivalent, but slower: 这是另一种等效的方法,但速度较慢:

where trunc(earliest_monthly_date) = to_date('2014-03-14', 'yyyy-mm-dd')

The trunc function takes away the time portion, but using functions in the where clause like this is slower than using the fields themselves. trunc函数占用了时间部分,但是像这样使用where子句中的函数比使用字段本身要慢。

You should also realize that dates are essentially floating point numbers. 您还应该意识到,日期本质上是浮点数。 They are formatted into strings so they can be read by humans. 它们被格式化为字符串,因此人类可以读取它们。 You can do your own formatting as well. 您也可以进行自己的格式化。 In oracle, the to_char() function is the one to use. 在oracle中,to_char()函数是要使用的函数。

Looking at the code in your question, there are three syntax errors. 查看问题中的代码,有三个语法错误。 First, 第一,

COUNT(DISTINCT(NETID)) 

should be 应该

COUNT(DISTINCT NETID)   

Next, it should be followed by a comma, 接下来,应在其后加上逗号,

COUNT(DISTINCT NETID),

and finally, you need a group by clause 最后,您需要一个group by子句

group by earliest_monthly_date

That's the syntax. 这就是语法。 What you probably want is something like this: 您可能想要的是这样的东西:

select to_char(earliest_monthly_date, 'yyyy-mm-dd') thedate
, count(distinct netid) countOfNetId
from report_service_usage
where earliest_monthly_date >= to_date('2014-03-14', 'yyyy-mm-dd')
and earliest_monthly_date < to_date('2014-03-15', 'yyyy-mm-dd')
group by to_char(earliest_monthly_date, 'yyyy-mm-dd')

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

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