Working with dates in Oracle SQL

后端 未结 3 1502
一向
一向 2021-01-22 11:58

I am very new when it comes to using SQL and what I am attempting to do is select the waterUsage and electrcityUsage using only the month and year and select the waterUsage and

3条回答
  •  难免孤独
    2021-01-22 12:48

    Assuming that billingdate is a DATE column.

    You can't compare a DATE with a string value. If you only want to compare "parts" of a date you need to convert the date to a string:

    select electrcityUsage, waterUsage 
    from monthlyBill
    where accountNumber ='211' 
      and to_char(billingDate,'MM-YY') = '12-12'
    

    But I would strongly recommend to always use four digit years:

    select electrcityUsage, waterUsage 
    from monthlyBill
    where accountNumber ='211' 
      and to_char(billingDate,'MM-YYYY') = '12-2012'
    

    or use the extract function:

    select electrcityUsage, waterUsage 
    from monthlyBill
    where accountNumber ='211' 
      and extract(month from billingDate) = 12 
      and extract(year from billingdate) = 2012;
    

    To get the previous year, subtract a year, but you need to take into account that in Oracle a DATE always contains a time as well (despite the name of the data type). To set the time to 00:00:00 use trunc()

    select electrcityUsage, waterUsage 
    from monthlyBill
    where accountNumber ='211' 
      and trunc(billingdate) = trunc(sysdate - interval '1' year);
    

提交回复
热议问题