如何使用oracle

时间:2017-06-14 05:23:13

标签: sql oracle select

在我的表customer_records中,有一个StartDate列,其值为DDMMYYYYHHMMSS格式(列数据类型为VARCHAR)。
我想以YYYYMM格式的日期从表组中提取数据。

我有以下工作查询:它将以MMYYYY格式提取数据。

SELECT /*+ PARALLEL(a , 8 ) */
          NVL (SUBSTR (StartDate, 3, 6), 'Total') "Year-Month",Started",
         TO_CHAR (COUNT (1), '999,999,999') "Customer Count",
         TO_CHAR (
              SUM (Usage)/60,
            '999,999,999')`enter code here`
            "Duration (M)"
    FROM customer_records a
   WHERE type='NEW'
          and customer_status=0 
GROUP BY ROLLUP (to_date(SUBSTR (StartDate, 3, 6),'MMYYYY'), 'Total')
ORDER BY 1;

但我希望日期格式为YYYYMM格式 我尝试了以下选项。但没有工作,

SELECT /*+ PARALLEL(a , 8 ) */
        NVL (to_date(SUBSTR (StartDate, 3, 6),'MMYYYY'), 'Total') "Month Started",
         TO_CHAR (COUNT (1), '999,999,999') "Customer Count",
         TO_CHAR (
              SUM (Usage)/60,
            '999,999,999')
            "Duration (M)"
    FROM customer_records a
   WHERE type='NEW'
          and customer_status=0 
GROUP BY ROLLUP (to_date(SUBSTR (StartDate, 3, 6),'MMYYYY'), 'Total')
ORDER BY 1;

有人可以帮我编辑上面的查询以获取YYYYMM格式的数据吗?

2 个答案:

答案 0 :(得分:1)

如果给定的startdate是日期格式,那么下面的一个将运行良好。

更新:正如您在评论中提到的那样,它不是数据格式,那么您首先将其转换为日期格式,然后使用to_char函数将其转换为YYYYMM格式

SELECT /*+ PARALLEL(a , 8 ) */
            NVL ( to_CHAR(to_date(substr(StartDate, 1,8),'DDMMYYYY'),'YYYYMM'),'Total') "Month Started",
             TO_CHAR (COUNT (1), '999,999,999') "Customer Count",
             TO_CHAR (
                  SUM (Usage)/60,
                '999,999,999')
                "Duration (M)"
        FROM customer_records a
       WHERE type='NEW'
              and customer_status=0 
    GROUP BY ROLLUP (to_CHAR(to_date(substr(StartDate, 1,8),'DDMMYYYY'),'YYYYMM'))
    ORDER BY 1;

答案 1 :(得分:-1)

你可以尝试:::

select TO_DATE(TO_CHAR(StartDate, 'MM/YYYY'), 'MM/YYYY') mmyyyyFormatDate from customer_records ;  --get the date in mm/yyyy format