如何优化此 SQL 查询?
(SELECT SUM (same_field) FROM same_table WHERE other_same_field = '0') AS a,
(SELECT SUM (same_field) FROM same_table WHERE other_same_field = '1') AS b,
(SELECT SUM (same_field) FROM same_table WHERE other_same_field = '2') AS c
如何优化此 SQL 查询?
(SELECT SUM (same_field) FROM same_table WHERE other_same_field = '0') AS a,
(SELECT SUM (same_field) FROM same_table WHERE other_same_field = '1') AS b,
(SELECT SUM (same_field) FROM same_table WHERE other_same_field = '2') AS c
当你想在 MySQL 中做一个数据透视时,你可以在 Case 语句上做 Aggregate
SELECT
SUM ( CASE WHEN other_same_field = 0 THEN same_field ELSE 0 END) as A,
SUM ( CASE WHEN other_same_field = 1 THEN same_field ELSE 0 END) as B,
SUM ( CASE WHEN other_same_field = 2 THEN same_field ELSE 0 END) as C
FROM same_table
WHERE other_same_field IN (0, 1, 2)
这会给你一个垂直的结果。
SELECT other_same_field, SUM(same_field)
FROM same_table
WHERE other_same_field IN (0, 1, 2)
GROUP BY other_same_field