我有这张桌子->
+----+-----------+-----------+
| id | gainOnX | gainOnY |
+----+-----------+-----------+
| 1 | 10 | 10 |
| 1 | -5 | 5 |
| 2 | -5 | -10 |
| 2 | -10 | 5 |
+----+-----------+-----------+
Run Code Online (Sandbox Code Playgroud)
我需要按 id 对这些数据进行分组,但我需要 4 列
所以它应该看起来像这样 ->
+----+---------+-------+---------+-------+
| id | profitX | lossX | profitY | lossY |
+----+---------+-------+---------+-------+
| 1 | 10 | -5 | 15 | 0 |
| 2 | 0 | -15 | 5 | -10 |
+----+---------+-------+---------+-------+
Run Code Online (Sandbox Code Playgroud)
我认为你只想要条件聚合:
select id,
sum(case when gainOnX > 0 then gainOnX else 0 end),
sum(case when gainOnX < 0 then gainOnX else 0 end),
sum(case when gainOnY > 0 then gainOnY else 0 end),
sum(case when gainOnY < 0 then gainOnY else 0 end)
from t
group by id;
Run Code Online (Sandbox Code Playgroud)