我遇到这样的情况:
----------------------------------------------
| id | subject | type | value |
==============================================
| 1 | AAA | IN | 900.00 |
| 2 | BBB | IN | 200.00 |
| 3 | BBB | OUT | 140.00 |
| 4 | AAA | OUT | 650.00 |
| 5 | BBB | IN | 90.00 |
| 6 | CCC | OUT | 50.80 |
| 7 | AAA | OUT | 480.40 |
| 8 | CCC | IN | 645.20 |
| 9 | CCC | OUT | 111.80 |
|--------|----------|------------|-----------|
我需要根据类型将所有值求和,并显示每个主题的结果,因此所需结果必须是:
----------------------------------------
| subject | income(IN) | outcome(OUT) |
========================================
| AAA | 900.00 | 1130.40 |
| BBB | 290.00 | 140.00 |
| CCC | 645.20 | 162.60 |
其中收入(IN)列显示类型为IN的每个主题的总和,结果列(OUT)也是如此。 我尝试了几次查询,但没有成功。
请您帮忙。提前致谢。
答案 0 :(得分:2)
您可以使用带有Group By
子句的Case..When
表达式来使用条件聚合:
SELECT
subject,
SUM(CASE WHEN type = 'IN' THEN value END) AS income,
SUM(CASE WHEN type = 'OUT' THEN value END) AS outcome
FROM your_table
GROUP BY subject
编辑:
从comments看来value
列的数据类型不是数字。它是字符串,可能带有逗号(由于数字格式)。我们将需要使用Replace()
函数将逗号替换为空字符串。然后,使用Cast()
将其转换为数值。
SELECT
subject,
SUM(CASE WHEN type = 'IN'
THEN CAST(REPLACE(value, ',', '') AS DECIMAL(11,2))
END) AS income,
SUM(CASE WHEN type = 'OUT'
THEN CAST(REPLACE(value, ',', '') AS DECIMAL(11,2))
END) AS outcome
FROM your_table
GROUP BY subject