jordaniac89
jordaniac89

Reputation: 574

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". I would like to be able to SELECT another column WHERE the date is XXXX/XX/XX without the time. I'm not very familiar with SQL, so I'm not exactly sure how to do this. 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.

Upvotes: 0

Views: 72

Answers (1)

Dan Bracuk
Dan Bracuk

Reputation: 20804

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.

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.

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 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')

Upvotes: 1

Related Questions