SQL查询:在行被反转时对ID进行求和。

huangapple go评论56阅读模式
英文:

SQL Query to sum ids whenever the rows are reverse

问题

以下是翻译好的内容:

my_table==>

id col1 col2
1 a b
2 b a
3 b a
4 c d
5 d c
6 x y

Expected Output==>

id col1 col2
6 a b
9 c d
6 x y

> 所以逻辑是每当col1和col2与前一个行的col2和col1相反时,添加id的总和!

SELECT t1.id + t2.id AS id_sum, t1.col1, t1.col2
FROM my_table t1
JOIN my_table t2 ON t1.col1 = REVERSE(t2.col2) AND t1.col2 = REVERSE(t2.col1)
WHERE t1.id < t2.id
ORDER BY id_sum;

英文:

my_table==>

id col1 col2
1 a b
2 b a
3 b a
4 c d
5 d c
6 x y

Expected Output==>

id col1 col2
6 a b
9 c d
6 x y

> So the logic is whenever there is col1 and col2 is reversed for previous add the ids!

 SELECT t1.id + t2.id AS id_sum, t1.col1, t1.col2
 FROM my_table t1
 JOIN my_table t2 ON t1.col1 = REVERSE(t2.col2) AND t1.col2 = REVERSE(t2.col1)
 WHERE t1.id &lt; t2.id
 ORDER BY id_sum;

答案1

得分: 0

这是你想要的吗?

选择 sum(id) 作为 id,least(col1, col2) 作为 col1,greatest(col1, col2) 作为 col2
从 mytable t
按 least(col1, col2) 和 greatest(col1, col2) 分组

这个想法是取两列中的最小/最大值,并使用该信息对数据集进行分组。

这将为你的示例数据生成期望的结果。

英文:

Is this what you want?

select sum(id) as id, least(col1, col2) col1, greatest(col1, col2) col2
from mytable t
group by least(col1, col2), greatest(col1, col2)

The idea is to take the least/greatest value amongst the two columns, and use that information to group the dataset.

This would produce your expected results for your sample data.

huangapple
  • 本文由 发表于 2023年4月17日 17:28:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76033633.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定