Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

แยกผลรวมค่าบวกและค่าลบในคอลัมน์เดียวเป็นคอลัมน์ต่างหากใน MySQL

ใช้ CASE WHEN ภายใน SUM() เพื่อแยกคำนวณค่าบวกและค่าลบ

สร้างตารางและเพิ่มข้อมูล

mysql> create table DemoTable( 
    Id int, 
    Value int ); 
Query OK, 0 rows affected (0.51 sec)

mysql> insert into DemoTable values(10,100); Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(10,-110); Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(10,200); Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(10,-678); Query OK, 1 row affected (0.17 sec)

แสดงข้อมูล

mysql> select * from DemoTable;
+------+-------+
| Id   | Value |
+------+-------+
| 10   | 100   |
| 10   | -110  |
| 10   | 200   |
| 10   | -678  |
+------+-------+
4 rows in set (0.00 sec)

คิวรีแยกผลรวมบวก/ลบ

mysql> select Id, 
    sum(case when Value > 0 then Value else 0 end) as Positive_Value, 
    sum(case when Value < 0 then Value else 0 end) as Negative_Value 
    from DemoTable 
    group by Id;
+------+----------------+----------------+
| Id   | Positive_Value | Negative_Value |
+------+----------------+----------------+
| 10   | 300            | -788           |
+------+----------------+----------------+
1 row in set (0.00 sec)

การคำนวณ: บวก: 100+200=300, ลบ: -110+(-678)=-788