使用Oracle LISTAGG函数添加编号的项目符号

时间:2015-11-05 09:02:34

标签: sql oracle listagg

是否可以使用Oracle的LISTAGG函数添加编号的项目符号?

即:

我有一张桌子:

PRODUCT_ID    PRODUCT_NAME
1001          Bananas
1002          Apples
1003          Pears
1004          Oranges

SQL语句:

SELECT LISTAGG('*' || product_name, CHR(13)) WITHIN GROUP (ORDER BY product_name) "Product_Listing"
FROM products;

*是一个编号的子弹,应该产生ff:

1. Apples
2. Bananas
3. Oranges
4. Pears

此外,是否可以使用字母而不是数字?

3 个答案:

答案 0 :(得分:2)

您可以在子查询中使用row_number()来生成数字

SELECT LISTAGG(rownum||'. '|| product_name, CHR(13)) WITHIN GROUP (ORDER BY product_name) "Product_Listing" 
FROM
   (SELECT product_id, product_name
      FROM products
     ORDER BY product_name)

或rownum

UIView

答案 1 :(得分:1)

Product_Listing_1为您提供了数字项目符号,Product_Listing_2为您提供了字母项目符号。

with products as (
    select 1001 as product_id, 'Bananas' as product_name from dual
    union all
    select 1002 as product_id, 'Apples' as product_name from dual
    union all
    select 1003 as product_id, 'Pears' as product_name from dual
    union all
    select 1004 as product_id, 'Oranges' as product_name from dual
),
make_bullets$ as (
    select X.*,
        row_number() over (partition by null order by product_name) as the_number_bullet,
        chr(ascii('a') - 1 + row_number() over (partition by null order by product_name)) as the_letter_bullet
    from products X
)
select
    listagg(the_number_bullet||'. '||product_name, chr(13)) within group (order by product_name) as "Product_Listing_1",
    listagg(the_letter_bullet||'. '||product_name, chr(13)) within group (order by product_name) as "Product_Listing_2"
from make_bullets$
;

结果:

Product_Listing_1    Product_Listing_2
-----------------    -----------------
1. Apples            a. Apples
2. Bananas           b. Bananas
3. Oranges           c. Oranges
4. Pears             d. Pears

答案 2 :(得分:1)

我根本没有理由使用LISTAGG。 LISTAGG用于字符串聚合,您根本不需要聚合。

您可以使用 ROW_NUMBER()分析函数和连接运算符 ||来获得所需的输出。

例如,

SQL> WITH DATA AS(
  2  SELECT 1001 PRODUCT_ID, 'Bananas' PRODUCT_NAME FROM dual UNION ALL
  3  SELECT 1002, 'Apples' FROM dual UNION ALL
  4  SELECT 1003, 'Pears' FROM dual UNION ALL
  5  SELECT 1004, 'Oranges' FROM dual
  6  )
  7  SELECT row_number() OVER(ORDER BY product_name)||'. '||product_name my_bullet_list
  8  FROM DATA;

MY_BULLET_LIST
-------------------------------------------------
1. Apples
2. Bananas
3. Oranges
4. Pears

如果您不关心行的排序,可以使用 ROWNUM 伪列。