2016-04-27 123 views
2

嗨我有表列ID和日期我想制作另一列按季度存储日期。如何按日期按季度分组

例如

ID DATES 

123 5/1/2005 
123 7/1/2001 
123 4/1/2003 
123 2/1/2002 
123 6/1/2005 
123 6/1/2004 

预期输出:

ID DATES  QUATER 

123 5/1/2005 Q2-2005 
123 7/1/2001 Q3-2001 
123 4/1/2003 Q2-2003 
123 2/1/2002 Q1-2002 
123 6/1/2005 Q2-2005 
123 6/1/2004 Q2-2004 

回答

1

你可以用to_char()做到这一点,就像这样:

with sample_data as (select 123 id, to_date('05/01/2005', 'mm/dd/yyyy') dt from dual union all 
        select 123 id, to_date('07/01/2001', 'mm/dd/yyyy') dt from dual union all 
        select 123 id, to_date('04/01/2003', 'mm/dd/yyyy') dt from dual union all 
        select 123 id, to_date('02/01/2002', 'mm/dd/yyyy') dt from dual union all 
        select 123 id, to_date('06/01/2005', 'mm/dd/yyyy') dt from dual union all 
        select 123 id, to_date('06/01/2004', 'mm/dd/yyyy') dt from dual) 
---- end of mimicking a table called sample_data that has your input data in it. See SQL below: 
select id, 
     dt, 
     TO_CHAR(sd.dt, '"Q"q-yyyy') qtr 
from sample_data sd; 

     ID DT   QTR  
---------- ---------- ------- 
     123 05/01/2004 Q2-2005 
     123 07/01/2001 Q3-2001 
     123 04/01/2003 Q2-2003 
     123 02/01/2002 Q1-2002 
     123 06/01/2005 Q2-2005 
     123 06/01/2004 Q2-2004