两个日期之间的SQL查询,甚至显示不在之间的日期

时间:2016-09-01 06:02:10

标签: sql oracle date between

select ktl.id, kth.trans_dte, kth.trtype, kp.match_code,ktl.net_amount,ktl.gross_amount,ktl.db_portfolio_type,ktl.cr_portfolio_type from k$transaction_lines ktl 
    left join k$transaction_header kth on ktl.id=kth.id 
    left join k$portfolio kp on kp.id = (CASE WHEN ktl.db_portfolio_type = 'C' THEN ktl.db_portfolio ELSE ktl.cr_portfolio END) 
    where to_char(kth.trans_dte,'DD-MON-YY') >= '22-AUG-16' 
    and to_char(kth.trans_dte,'DD-MON-YY') <= '27-AUG-16'
    and ktl.db_portfolio_type <> 'I' 
    and ktl.cr_portfolio is not null 
    order by  kth.trans_dte, ktl.id, kp.match_code, kth.trtype

这是我的查询。我只是想知道我的where子句kth.trans_dte是否有问题。 我只想在8月22日到8月27日之间获得交易,但是我在那个日期之前得到了交易,2月和3月的交易都包含在他们不应该的时候。我想知道为什么..我的代码是否有问题,或者是我不知道的数据库的问题。谢谢!

5 个答案:

答案 0 :(得分:1)

you convert your field to char with to_char and then try to compare it datewise. to_char does exactly what it says - converts to a char string so you'll get dates according to ascii representation of the string

try using to_date instead - on both sides of the condition (s)

答案 1 :(得分:0)

尝试使用BETWEEN而不是2个条件。

答案 2 :(得分:0)

select ktl.id, kth.trans_dte, kth.trtype, kp.match_code,ktl.net_amount,ktl.gross_amount,ktl.db_portfolio_type,ktl.cr_portfolio_type from k$transaction_lines ktl 
    left join k$transaction_header kth on ktl.id=kth.id 
    left join k$portfolio kp on kp.id = (CASE WHEN ktl.db_portfolio_type = 'C' THEN ktl.db_portfolio ELSE ktl.cr_portfolio END) 
    where (to_char(kth.trans_dte,'DD-MON-YY') >= '22-AUG-16' 
    and to_char(kth.trans_dte,'DD-MON-YY') <= '27-AUG-16')
    and ktl.db_portfolio_type <> 'I' 
    and ktl.cr_portfolio is not null 
    order by  kth.trans_dte, ktl.id, kp.match_code, kth.trtype

试试这个。

答案 3 :(得分:0)

try using between Keyword and to_date function in Query like

where kth.trans_dte between to_date('22-AUG-16') 
and to_date('27-AUG-16')
and ktl.db_portfolio_type <> 'I' 
and ktl.cr_portfolio is not null 
order by  kth.trans_dte, ktl.id, kp.match_code, kth.trtype

答案 4 :(得分:0)

Sorry, I solved it just now. I can't use to_char when doing that condition that is why it gives the wrong results.