Labels

Script categories

Showing posts with label Date/Time calculations. Show all posts
Showing posts with label Date/Time calculations. Show all posts

Thursday, 29 September 2011

pipelined Date function

The requirement for this function is to
list the months ahead of the month supplied as parameters (both  numbers).
The number of months ahead of the month supplied would also
be supplied as a parameter.


create or replace type dtTable as table of date;
/
create or replace function p (pYear       in number
                             ,pMonth      in number
                             ,pMth_Ahead  in pls_integer) 
  return dtTable pipelined as

 l_In_Date date := to_date(to_char(pYear)||to_char(pMonth), 'yyyymm');

begin

  for i in (select add_months(l_In_Date,(level-1)) dt
            from dual
            connect by level <= pMth_Ahead) loop
    pipe row(i.dt);
  end loop;
  return;
end;
/
SQL> select p.column_Value as Month from  table(p(2008,9,6)) p;

MONTH
---------
01-SEP-08
01-OCT-08
01-NOV-08
01-DEC-08
01-JAN-09
01-FEB-09

6 rows selected.

Thursday, 22 September 2011

Show todays date in Arabic

select  to_char(sysdate, 'DD-Mon-YYYY')                     Today
       ,to_char(sysdate,'dd mon rrrr'
                      ,'nls_calendar = ''english hijrah''') Arabic_Day
from dual
/
TODAY                ARABIC_DAY
-------------------- -------------------------
22-Sep-2011          23 Shawwal           1432

Calculating Age and grouping into Age groups

-- Grouping people in a specific age group
with t as
(
select 'john' name,to_date('01.01.1990','dd.mm.yyyy') birth_date from dual union
select 'sue',      to_date('02.05.2000','dd.mm.yyyy')  from dual union
select 'abraham',  to_date('04.07.1998','dd.mm.yyyy')  from dual union
select 'Tim',      to_date('15.09.1998','dd.mm.yyyy')  from dual union
select 'Rob',      to_date('16.09.1998','dd.mm.yyyy')  from dual union
select 'Mary',     to_date('14.09.1990','dd.mm.yyyy')  from dual union
select 'Larry',    to_date('16.09.1995','dd.mm.yyyy')  from dual union
select 'Sally',    to_date('16.09.1965','dd.mm.yyyy')  from dual
)
--
select age_group , count(*)
from
(
  select
    case
      when trunc( months_between(sysdate, birth_date) / 12 ) <= 17 then
        '0-17'
      when trunc( months_between(sysdate, birth_date) / 12 ) <= 24 then
        '18-24'
      when trunc( months_between(sysdate, birth_date) / 12 ) <= 34 then
        '25-34'
      when trunc( months_between(sysdate, birth_date) / 12 ) <= 44 then
        '35-44'
      when trunc( months_between(sysdate, birth_date) / 12 ) <= 54 then
        '45-54'
      else 'n/a'
    end age_group
  from t
)
group by age_group
order by age_group;