0

我有一个查询,它返回以下结果......

SELECT wk, cost FROM my_table WHERE id = '234' order by week

WK  COST
--------
17  446
18  446
19  446
26  588
27  588
28  588

我需要尝试做的是编写一个查询来实现以下结果......

WKS           COST
------------------
17, 18, 19    446
26, 27, 28    588

这可能吗?

4

3 回答 3

3

像这样试试

WITH t(wk, COST) AS
(
SELECT 17,  446 FROM dual
UNION 
SELECT 18,  446 FROM dual
UNION 
SELECT 19,  446 FROM dual
UNION 
SELECT 26,  588 FROM dual
UNION 
SELECT 27,  588 FROM dual
UNION 
SELECT 28,  588 FROM dual
)
SELECT listagg(wk,',') WITHIN GROUP(ORDER BY wk) AS wks, COST 
FROM   t
GROUP BY COST;
于 2013-10-09T10:12:44.843 回答
0

如果不使用oralce 11g,那么您需要使用以下解决方案,否则@Dba 回答

  WITH t AS
     (SELECT 17 wk, 446 COST
        FROM DUAL
      UNION
      SELECT 18 wk, 446 COST
        FROM DUAL
      UNION
      SELECT 19 wk, 446 COST
        FROM DUAL
      UNION
      SELECT 26 wk, 588 COST
        FROM DUAL
      UNION
      SELECT 27 wk, 588 COST
        FROM DUAL
      UNION
      SELECT 28 wk, 588 COST
        FROM DUAL)
SELECT     COST,
           LTRIM
              (MAX (SYS_CONNECT_BY_PATH (wk, ','))KEEP (DENSE_RANK LAST ORDER BY curr),
               ','
              ) AS COST
      FROM (SELECT wk, COST,
                   ROW_NUMBER () OVER (PARTITION BY COST ORDER BY wk) AS curr,
                     ROW_NUMBER () OVER (PARTITION BY COST ORDER BY wk)
                   - 1 AS prev
              FROM t)
  GROUP BY COST
CONNECT BY prev = PRIOR curr AND COST = PRIOR COST
START WITH curr = 1;
于 2013-10-09T10:19:17.243 回答
0
By using LISTAGG function you can achieve what you are trying to do.       

 SELECT deptno
        ,LISTAGG(sal, '-') WITHIN GROUP (ORDER BY sal) AS employees
           FROM   emp
            GROUP  BY
                   deptno;

    -----------------------------------------------------
    OUTPUT
    -----------------------------------------------------
    DEPTNO EMPLOYEES 
    10     1300-2450-5000 
    20     800-1100-2975-3000-3000 
    30     950-1250-1250-1500-1600-2850 

    3 rows returned in 0.01 seconds        
于 2013-11-15T11:07:00.650 回答