如何在DB2 sql中获取重复的子字符串

时间:2017-10-04 04:28:42

标签: sql db2

如何在DB2 sql中获取重复的子字符串 我的情况是,我有一栏

col1

| ABC_1      |

| ABC_3      |

|  WXY_5     |

我想只获得重复的子字符串数据,并添加剩余的子值

    String       addn of substring values

|   ABC        | |     4       |

|   WXY        | |     5       |

4是为我使用的查询添加了重复的子字符串值SUM(CAST(SUBSTR(a.ref1, LOCATE('-',a.ref1)+1) as DECIMAL))作为输出

但该怎么做?

请给我一个建议吗?

3 个答案:

答案 0 :(得分:0)

试试这个:

with formatedtable as (
select 
left(a.ref1, LOCATE('_',a.ref1) - 1) as String, 
CAST(SUBSTR(a.ref1, LOCATE('_',a.ref1)+1) as DECIMAL) valdec
from yourtable a
)
select String, sum(valdec) total 
from formatedtable
group by String

如果你不是总是在你的字符串中存在数字,试试这个:

with formatedtable as (
select 
left(a.ref1, LOCATE('_',a.ref1) - 1) as String, 
CAST(SUBSTR(a.ref1, LOCATE('_',a.ref1)+1) as DECIMAL) valdec
from yourtable a
where LOCATE('_',a.ref1)>0 and trim(SUBSTR(a.ref1, LOCATE('_',a.ref1)+1))<>'' 
and trim(translate(SUBSTR(a.ref1, LOCATE('_',a.ref1)+1), '          ', '0123456789'))='' 
)
select String, sum(valdec) total 
from formatedtable
group by String

答案 1 :(得分:0)

with formatedtable as (
select 
left(a.ref1, LOCATE('_',a.ref1) - 1) as String, 
CAST(SUBSTR(a.ref1, LOCATE('_',a.ref1)+1) as DECIMAL) valdec
from 
(SELECT DISTINCT T1.PROJECT_NAME,
       T1.REFERENCE_ID,
       T1.NAME AS URL1_title,
       T1.URL AS URL1,
       T1.REQUEST_TYPE,

        T2.VAL AS owner1,

     T2.VAL  ||'-'|| cast(T3.VAL AS CHAR(10)) AS ref1 ,
       T4.VAL AS owner2,
     T4.VAL  ||'-'||  cast(T5.VAL AS CHAR(10)) AS ref2 ,
       T6.VAL AS owner3,
     T6.VAL  ||'-'|| cast(T7.VAL AS CHAR(10)) AS ref3
FROM RIDW.VW_REQUEST T1
LEFT OUTER JOIN RICALM.VW_RQST_STRING_EXT T2
ON T2.REQUEST_ID=T1.REQUEST_ID AND T2.NAME='owner_1'
  LEFT OUTER JOIN RICALM.VW_RQST_DECIMAL_EXT T3
  ON T3.REQUEST_ID=T1.REQUEST_ID AND T3.NAME='resource1'
    LEFT OUTER JOIN RICALM.VW_RQST_STRING_EXT T4
    ON T4.REQUEST_ID=T1.REQUEST_ID AND T4.NAME='owner_2'
      LEFT OUTER JOIN RICALM.VW_RQST_DECIMAL_EXT T5
      ON T5.REQUEST_ID=T1.REQUEST_ID AND T5.NAME='resource2'
        LEFT OUTER JOIN RICALM.VW_RQST_STRING_EXT T6
        ON T6.REQUEST_ID=T1.REQUEST_ID AND T6.NAME='owner_3'
          LEFT OUTER JOIN RICALM.VW_RQST_DECIMAL_EXT T7
          ON T7.REQUEST_ID=T1.REQUEST_ID AND T7.NAME='resource'
WHERE T1.PROJECT_ID = 0  AND
(  T1.REQUEST_TYPE = 'Task' 
) AND
(T1.ISSOFTDELETED = 0) AND
(T1.REQUEST_ID <> -1 AND T1.REQUEST_ID IS NOT NULL) ORDER BY T2.VAL asc,
         T4.VAL asc,
         T6.VAL asc)a
)
SELECT valdec as ref
      FROM formatedtable

答案 2 :(得分:0)

对于你的上一篇文章,我想你可以做到这一点:

SELECT T2.VAL, sum(T3.VAL) total 
FROM RIDW.VW_REQUEST T1
INNER JOIN RICALM.VW_RQST_STRING_EXT T2 ON T2.REQUEST_ID=T1.REQUEST_ID AND T2.NAME='owner_1' AND T1.REQUEST_ID <> -1 
INNER JOIN JOIN RICALM.VW_RQST_DECIMAL_EXT T3 ON T3.REQUEST_ID=T1.REQUEST_ID AND T3.NAME='resource1'
WHERE (T1.PROJECT_ID, T1.REQUEST_TYPE, T1.ISSOFTDELETED)  = (0,  'Task', 0) 
group by T2.VAL