How to categorize data for each date in sql?

时间:2015-11-12 11:20:35

标签: sql database oracle date date-arithmetic

I am using Oracle sql developer.And I have to categorize some data into each Date from a table.

I used TO_CHAR function to change the date format.

select to_char(txn_date, 'dd-mon-rrrr') my_day, some_coloums
from mwt_wallet_transactions 
order by my_day;

It's ok with upper one. But I want to get it with given date like this:

select to_char( txn_date, 'dd-mon-rrrr') my_day, some_coloums
from mwt_wallet_transactions 
where my_day like '08-feb-2015'
order by my_day;

I searched this over the internet, most of them asked to use the CONVERT function like this:

select convert (VARCHAR(10), txn_date , 23 )  my_day, some_colomns
from mwt_wallet_transactions 
where my_day like '08-feb-2015'
order by my_day;

But it doesn't work for me. Help me to solve this!

3 个答案:

答案 0 :(得分:6)

where my_day like '08-feb-2015'

I think you got confused between SELECTION and FILTER PREDICATE.

Also, remember, ''08-feb-2015' is NOT a DATE, it is a string.

You want to filter the rows based on a DATE value. So, convert the literal on the R.H.S. into DATE using TO_DATE or use ANSI Date literal if you don't have a time portion.

Now, remember, a DATE has both date and time elements, so you need to -

  • either use TRUNC on the date column to get rid off the time element
  • or, use a DATE range condition to for better performance as it would use any regular index on the date column.

I am assuming my_day as the date column. Modify the filter as:

Using ANSI Date literal: fixed format 'YYYY-MM-DD'

where my_day >= DATE '2015-02-08' and   my_day < DATE '2015-02-09'

Or, TO_DATE with proper format model. Remember, TO_DATE is NLS dependent, so I have used NLS_DATE_LANGUAGE to make it NLS independent.

WHERE my_day >= TO_DATE('08-feb-2015','dd-mon-yyyy','NLS_DATE_LANGUAGE=american') 
AND   my_day < TO_DATE('09-feb-2015','dd-mon-yyyy','NLS_DATE_LANGUAGE=american')

Above. my_day is assumed as the static date column, and not the column alias.

答案 1 :(得分:0)

You can't use select list column aliases in the WHERE clause. Use derived table to access it:

select * from
(
 select *some_computed_value* as my_day, some_colomns
 from mwt_wallet_transaction
) 
where *my_day conditions*
order by my_day

答案 2 :(得分:0)

我的解决方案:

我检查了这个解决方案并且运行良好,

select * from
(select cast( TRUNC(txn_date) as date) my_day ,some_columns
from mwt_wallet_transactions
)
where my_day = '08-FEB-15'
order by my_day
;

或者我们可以使用:

select * from
(select to_char( txn_date, 'dd-mon-rrrr') my_day 
from mwt_wallet_transactions
)
where my_day = '08-feb-2015'
order by my_day;