hitomitanaka 的語法 for mysql 是正確的;
另一語法
select name,sum(case WHEN cond=0 then col1 else 0 end) AS '加總欄位1',
sum(col2) AS '加總欄位2'
from ithelp040417
group by name
猜猜看是不是這樣.
<pre class="c" name="code">CREATE TABLE ithelp040417(
name CHAR(4) NOT NULL,
col1 INT UNSIGNED NOT NULL,
col2 INT UNSIGNED NOT NULL,
cond TINYINT NOT NULL
);
INSERT INTO ithelp040417(name, col1, col2, cond) VALUES
('張三', 100, 100, 0),
('李四', 500, 500, 0),
('張三', 800, 800, 1),
('李四', 500, 500, 1);
SELECT name
, SUM(IF(cond = 0,col1, 0)) AS '加總欄位1'
, SUM(col2) AS '加總欄位2'
FROM ithelp040417
GROUP BY name;
+--------+---------------+---------------+
| name | 加總欄位1 | 加總欄位2 |
+--------+---------------+---------------+
| 張三 | 100 | 900 |
| 李四 | 500 | 1000 |
+--------+---------------+---------------+