使用Sequence中的不同列数进行连接

时间:2012-01-27 11:09:53

标签: sql oracle string-concatenation

我有以下查询

select dated,sum(substr(hrs,1,2)) ||':'|| sum(substr(hrs,4,5)) hrs,dpt,reason
from dpr.stp_00_00
group by dated,dpt,reason
order by dated

返回:

DATED       HRS     DPT         REASON
10/14/2011  2:5     Mechanical  Boiler tubes damaged & less availability of steam 
10/14/2011  0:20    Mechanical  Breakage of link of bagasse carrier # 1 and surplus 
10/14/2011  1:0     Mechanical  Choke at belt conveyor 
10/15/2011  0:10    Mechanical  Boiler pressure dropped
10/16/2011  1:30    Electrical  Power failure / 505 governor card damaged of 
10/16/2011  0:10    Mechanical  3rd mill taken in line
10/16/2011  0:30    Mechanical  Raw juice line before primary heaters busted
10/16/2011  1:0     Mechanical  Raw juice pump at mill house NRV body got busted

此查询中的问题是我想在单行中显示每个日期的所有原因,以便所有原因应该在单行中显示单个日期例如对于14-OCT-2012,有三个原因具有相同的部门和同一个日期我想分组的原因,以便它将显示在单行像

Dated         HRS  DPT           Reason
10/14/2012    2:5  Mechanical    All Resons of all 14 oct

任何人都可以告诉我如何使用sql查询或任何用户定义的函数

2 个答案:

答案 0 :(得分:3)

您可以找到类似的问题,并就该主题here提供答案。

此外,Tom Kyte编写了一个名为stragg的函数来执行此操作 - 您可以找到here,尽管他随后提供了另一种方法here

答案 1 :(得分:0)

请试试这个

CREATE OR REPLACE FUNCTION concatenate_list (p_cursor IN  SYS_REFCURSOR)
  RETURN  VARCHAR2
IS
  l_return  VARCHAR2(32767);
  l_temp    VARCHAR2(32767);
BEGIN
  LOOP
    FETCH p_cursor
    INTO  l_temp;
--    EXIT WHEN p_cursor%NOTFOUND;
    l_return := l_return ||   '  ,' || l_temp;
  END LOOP;
  RETURN LTRIM(l_return, ',');
END;
/


SELECT dated,dpt,
       concatenate_list(CURSOR(SELECT e2.reason FROM dpr.stp_00_00 e2 WHERE e2.dated = e1.dated and e1.dpt=e2.dpt)) Reasons
FROM   (SELECT DISTINCT dpt,dated
        FROM dpr.stp_00_00 order by dated) e1;

希望这会有所帮助