在oracle中使用varchar字段时出错

时间:2013-12-11 15:14:43

标签: sql oracle11g

我有一张桌子 id和value都是varchars

>> id          "value"
-----------------------
   a             1
   a             2
   a             5
   a             6
   a             7
   a             8
   b             4
   b             5
   b             6
   b             9

我只想看输出

value    Result
-----------------
a        1-2,5,6-8
b        4-6,9

我尝试使用ListAGG()函数

将错误“value”作为无效标识符

SELECT
      LISTAGG ( TXT,
              ', ' )
      WITHIN GROUP (ORDER BY "value")
          "Result"
FROM
      (SELECT
            CASE
                WHEN MIN ( "value" ) = MAX ( "value" )
                THEN
                    CAST ( MIN ( "value" ) AS VARCHAR2 ( 400 ) )
                ELSE
                       MIN ( "value" )
                    || '-'
                    || MAX ( "value" )
            END
                AS TXT,
            MIN ( "value" ) AS SOURCE
       FROM
            (SELECT
                   ROW_NUMBER ( ) OVER (ORDER BY MIN ( "value" ))
                   - TO_NUMBER ( "value" )
                       AS GRP
             FROM
                   TABL2)
       GROUP BY
            GRP);

我猜是否有任何类型不匹配.. ?? 你能帮帮我吗...

1 个答案:

答案 0 :(得分:2)

代码存在许多问题。但是错误的原因是你没有在子查询的SELECT中包含value

我还注意到你缺少PARTITION BY id,这是进行你想要的分组所​​必需的。您也没有在外部查询中按id进行分组。

此查询:

SELECT id,
      LISTAGG ( TXT,', ' )
      WITHIN GROUP (ORDER BY source)"Result"
FROM
      (SELECT id,
            CASE
                WHEN MIN ( "value" ) = MAX ( "value" )
                THEN
                    CAST ( MIN ( "value" ) AS VARCHAR2 ( 400 ) )
                ELSE
                       MIN ( "value" )
                    || '-'
                    || MAX ( "value" )
            END
                AS TXT,
            MIN ( "value" ) AS SOURCE
       FROM (
            SELECT id,"value",
                   ROW_NUMBER ( )  OVER (partition by id ORDER BY MIN ( "value" ))
                   - TO_NUMBER ( "value" )
                       AS GRP
             FROM
                   TABL2
             GROUP BY id,"value"
       )
       GROUP BY
            id,GRP)
GROUP BY id

产地:

a   1-2, 5-8
b   4-6, 9

SQLFiddle here