如何在结果数据中添加字母

时间:2013-07-15 09:24:16

标签: sql oracle

当我运行以下查询时,

select
 NVL(week, 'SUM) week
  , sum(A) AS A, sum(B) AS B
from
  (
  select b.* 
     from TABLE  b
    where b.week between '2013051' and '2013052'
  )
 group by ROLLUP(WEEK)

我得到像

这样的数据
   |  WEEK  | 

    2013051

    2013052

但我想要将数据命名如下。

   |  WEEK  | 

2013. 05. 1 WEEK 

2013. 05. 2 WEEK

任何人都可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:5)

假设week是一个字符串:

select substr(week, 1, 4)
    ||'. '|| substr(week, 5, 2)
    ||'. '|| substr(week, 7, 1) ||' WEEK' as week,
...

或者如果week可以为null(由于您的子查询的过滤器,它不能从您的数据中获取,但是您从我最初错过的rollup中获得了生成的空值):

select case when week is null then 'SUM'
    else substr(week, 1, 4)
        ||'. '|| substr(week, 5, 2)
        ||'. '|| substr(week, 7, 1) ||' WEEK' end as week,
...

WEEK                      A          B
---------------- ---------- ----------
2013. 05. 1 WEEK          1          2 
2013. 05. 2 WEEK          3          4 
SUM                       4          6 

SQL Fiddle demo;还有一个without the subquery,这在这里似乎是多余的。

答案 1 :(得分:1)

如果您的Oracle RDBMS版本为10g或更高版本,regexp_replace函数也可用于执行自定义字符串格式设置:

select regexp_replace( 
         week, -- if week is of varchar2 datatype or to_char(week) if it's of number datatype
         '^([[:digit:]]{4})([[:digit:]]{2})([[:digit:]]{1})$', '\1. \2. \3  WEEK'
       )
  from your_table_name_or_subquery

结果:

WEEK    
------------------
2013. 05. 1 WEEK 
2013. 05. 2 WEEK