我有一个正面和正面的专栏负数。是否可以将Col1中的所有正数与Col2中的负数和Col3中的(Col1-Col2)相加。然后按最后一个Col。
排序 Current table New Table
ID Score ID Pos Neg Diff
1 3 3 5 0 5
1 1 1 4 1 3
1 -1 2 2 1 1
2 1
2 -1
2 1
3 3
3 1
3 1
这给了我总数,但我也想列出Pos和Neg数字。
SELECT ID, SUM(Score) as total FROM results
GROUP BY ID ORDER BY total DESC
答案 0 :(得分:3)
只需使用带有单独条件聚合的标准数据透视查询,即正数和负数。
SELECT
ID,
SUM(CASE WHEN Score >= 0 THEN Score ELSE 0 END) AS Pos,
SUM(CASE WHEN Score < 0 THEN -1*Score ELSE 0 END) AS Neg,
SUM(Score) AS Diff
FROM results
GROUP BY ID
ORDER BY ID