我在编写SQL时需要帮助,上下文是
- 示例数据如下所示:
a,b, count
1,2, 10
4,5, 20
2,1, 5
5,4, 6
6,7, 10
- 逻辑:
将a和b的行匹配到其反向行,即b和a(其中a = b和b = a),例如对于1,2行,2,1行被反转,它们之间预期的总计数是15
预期结果集:
1,2 15
4,5,26
6,7,10
或 2,1,15 4,5,26 6,7,10
要获得高于预期结果的任何简单SQL都会有所帮助。
答案 0 :(得分:0)
使用自我加入:
mysql> create table test (a integer, b integer, count integer);
Query OK, 0 rows affected (0.00 sec)
mysql> insert into test values(1,2,10);
Query OK, 1 row affected (0.00 sec)
mysql> insert into test values(4,5,20);
Query OK, 1 row affected (0.00 sec)
mysql> insert into test values(2,1,5);
Query OK, 1 row affected (0.00 sec)
mysql> insert into test values(5,4,6);
Query OK, 1 row affected (0.00 sec)
mysql> SELECT distinct a.a, a.b,a.count + b.count from test a
join test b on a.a = b.b where a.a< a.b;
+------+------+-------------------+
| a | b | a.count + b.count |
+------+------+-------------------+
| 1 | 2 | 15 |
| 4 | 5 | 26 |
+------+------+-------------------+
2 rows in set (0.00 sec)
mysql>