SQL"分裂"通过...分组

时间:2014-05-13 14:16:58

标签: mysql sql

我有下表:

('cat', 5000, 7000, 'A'),
('dog', 9200, 11000, 'A'),
('fog', 6500, 9300, 'B'),
('fox', 16001, 15001, 'B'),
('cat', 5005, 7005, 'B'),
('dog', 9299, 11399, 'B'),
('cat', 5005, 7005, 'B'),
('dog', 9299, 11399, 'B'),
('fox', 16001, 15002, 'A')

我需要通过第一列获得选择组,然后通过以下总和获得4列:

标志的col2,

col3 for A flag,

B标志的col2和

col标志为B标志。

我怎么能得到这个?

SQLFiddle

2 个答案:

答案 0 :(得分:3)

SELECT
    Animal,
    SUM(CASE WHEN flg = 'A' THEN V1 ELSE 0 END) AS A_V1,
    SUM(CASE WHEN flg = 'A' THEN V2 ELSE 0 END) AS A_V2,
    SUM(CASE WHEN flg = 'B' THEN V1 ELSE 0 END) AS B_V1,
    SUM(CASE WHEN flg = 'B' THEN V2 ELSE 0 END) AS B_V2
FROM
    MyTab
GROUP BY
    Animal

答案 1 :(得分:0)

select animal, 
    SUM(If(flg='A',V1,0)),
    SUM(If(flg='A',V2,0)),
    SUM(If(flg='B',V1,0)),
    SUM(If(flg='B',V2,0))
from MyTab
group by animal