oracle SQL用于合并两行并聚合[重复]

63lcw9qa  于 2023-10-16  发布在  Oracle
关注(0)|答案(1)|浏览(92)

此问题已在此处有答案

Grouping by pairs of values that are interchangeably used(2个答案)
8天前关闭
我试图写一个SQL查询下表中的前两行需要合并和给予输出为10|| 20 ||100.

from_id to_id duration
10 20 50
20 10 50
10 30 80
20 40 50
20 40 60

需求低于产出

from_id to_id total_duration
10 20 100
10 30 80
20 40 110

我尝试了下面的方法,但没有得到正确的输出。

select from_id,to_id,sum(total_duration) from table group by from_id,to_id;

from_id to_id total_duration
10 20 50
20 10 50
10 30 80
20 40 110
os8fio9y

os8fio9y1#

您希望将元组(10,20)和(20,10)视为同一个元组。为此,请使用LEASTGREATEST对它们进行排序:

select 
  least(from_id, to_id) as id1,
  greatest(from_id, to_id) as id2,
  sum(total_duration)
from table
group by least(from_id, to_id), greatest(from_id, to_id)
order by least(from_id, to_id), greatest(from_id, to_id);

相关问题