oracle中如何连接连续的行

Posted

技术标签:

【中文标题】oracle中如何连接连续的行【英文标题】:How to concatenate consecutive rows in oracle 【发布时间】:2019-09-21 05:46:00 【问题描述】:

我是甲骨文的初学者。我尝试按照源代码解决并得到以下O / P。但是不能,请给出一些想法来解决这个问题。

id    product                      sales
---  -------------                --------
   1      Soaps                     1200
   2      Ice cream                 2300
   3      Cool drinks               2500
   4      Tv                        5000
   5      Mobile                   10000
   6      Washing machine          20000```

```O/P
   id    product                   sales
   ---  -------------             --------
   1      Soaps                     1200
   2      Ice cream+Cool drinks     4800
   3      Tv+Mobile                15000 
   6      Washing machine          20000```

【问题讨论】:

作为提示,请阅读“窗口函数” 电视和手机是如何连接的?他们的类别是否有任何映射? 【参考方案1】:

必须有品类和产品的映射表。 必须映射具有类别的产品才能解决您的问题。

Select min(t.id) as id,
Listagg(t.product, ' + ') within group (order by t.id) as product,
Sum(t.sales) as sales
From your_table t
Join mapping_table m
On (m.product = t.product)
Group by m.catrgory;

干杯!!

【讨论】:

【参考方案2】:

你可以使用lead()解析函数:

with t1 as
(
select id, 
       concat(concat(product,'+'),lead(product) over (order by id)) as product,
       sales + lead(sales) over (order by id) as sales
  from tab -- your original table
), t2 as
(
select *
  from t1
 where id in (2,4) 
union all
select *
  from tab
 where id in (1,6) 
)
select * 
  from t2
 order by id;

Demo

【讨论】:

请accept 给出您认为最能回答您问题的答案。这样就明白问题的解决了@Naveen 当然是兄弟@Barbaros Özhan【参考方案3】:

我的事,您需要为分组依据添加列。请尝试:

WITH temp as (SELECT  1 id, 1 group_id, 'Soaps' str, 1200  as  price FROM dual
UNION ALL
SELECT  2 id, 2, 'Ice cream', 2300  FROM dual
UNION ALL
SELECT  3 id, 2, 'Cool drinks', 2300  FROM dual
UNION ALL
SELECT  4 id, 3, 'Tv', 5000  FROM dual
UNION ALL
SELECT  5 id, 3, 'Mobile', 10000  FROM dual
UNION ALL
SELECT  6 id, 4, 'Washing machine', 20000  FROM dual)
SELECT group_id, LISTAGG(str, ', ')
   WITHIN GROUP (ORDER BY group_id) "str",
   sum(price) price
FROM temp
GROUP BY  group_id

结果:

1   Soaps                   1200
2   Cool drinks, Ice cream  4600
3   Mobile, Tv              15000
4   Washing machine         20000

【讨论】:

以上是关于oracle中如何连接连续的行的主要内容,如果未能解决你的问题,请参考以下文章

oracle 怎么得到一个表中连续ID中断开的ID

PySpark - 如何根据列中的两个值从数据框中过滤出连续的行块

如何将连续的行与它们之间越来越多的重叠结合起来(就像滚动窗口一样)?

如何从MS SQL Server 2012中的不同表中减去连续的行?

数据库中怎么将一个字符串中的多个连续空格换成一个空格? oracle的存储过程中怎么样实现?

oracle中,查找存在任意三个相同且连续的字母的字符串,请问各位大神如何解决?