Oracle--SQL技巧之二(多行记录用逗号拼接在一起)

需求:

     目前接触BI系统,由于业务系统的交易记录有很多,常常有些主管需要看到所有的记录情况,但是又不想滚动,想一眼就可以看到所有的,于是就想到了字符串拼接的形式。

解决方案:使用Oracle自带的函数 WMSYS.WM_CONCAT,进行拼接。

函数限制:它的输出不能超过4000个字节。

为了不让SQL出错,又可以满足业务的需求,超过4000个字节的部分,使用“。。。”

实现SQL如下:

CREATE TABLE TMP_PRODUCT
(PRODUCT_TYPE VARCHAR2(255),
 PRODUCT_NAME VARCHAR2(255));
 
 
insert into tmp_product
select 'A','ProductA'||rownum from dual
connect by level < 100
union all
select 'B','ProductB'||rownum from dual
connect by level < 300
union all
select 'C','ProductC'||rownum from dual
connect by level < 400
union all
select 'D','ProductD'||rownum from dual
connect by level < 500
union all
select 'E','ProductE'||rownum from dual
connect by level < 600;


SELECT PRODUCT_TYPE,
       WM_CONCAT(PRODUCT_NAME) || MAX(STR) AS PRODUCT_MULTI_NAME
  FROM (SELECT PRODUCT_TYPE,
               PRODUCT_NAME,
               CASE
                 WHEN ALL_SUM > 4000 THEN
                  '...'
                 ELSE
                  NULL
               END AS STR
          FROM (SELECT PRODUCT_TYPE,
                       PRODUCT_NAME,
                       SUM(VSIZE(PRODUCT_NAME || ',')) OVER(PARTITION BY PRODUCT_TYPE) AS ALL_SUM,
                       SUM(VSIZE(PRODUCT_NAME || ',')) OVER(PARTITION BY PRODUCT_TYPE ORDER BY PRODUCT_NAME) AS UP_SUM
                  FROM TMP_PRODUCT)
         WHERE (UP_SUM <= 3998 AND ALL_SUM > 4000)
            OR ALL_SUM <= 4001)
 GROUP BY PRODUCT_TYPE

posted @ 2013-01-08 22:25  dct_it  阅读(4390)  评论(0编辑  收藏  举报