两列mysql的组列数的总和

时间:2011-10-12 10:49:40

标签: mysql count group-by sum

INSERT INTO tablex(Id, Name, Team, Joined) VALUES

(1, 'Mr. A', 'X', '2011-02-22'),

(2, 'Mr. B', 'Y', '2011-02-11'),

(3, 'Ms. C', 'X', '2011-02-10'),

(4, 'Mr. D', 'Y', '2011-01-12'),

(5, 'Ms. E', 'X', '2011-01-06'),

(6, 'Mr. F', 'Y', '2011-05-02');

(7, 'Mr. H', 'X', '2011-02-01');

所需的输出是:

Month   | Team | TotalMembers | Percentage

 01/2011  | X    |   1          |   50

 01/2011  | Y    |   1          |   50

 02/2011  | X    |   2          |   75

 02/2011  | Y    |   1          |   25

 05/2011  | X    |   0          |   0

 05/2011  | Y    |   1          |   100

请帮我完成上述操作。在MySQL中最受欢迎(GROUP BY Team,DATE_FORMAT(已加入,'%m /%Y'))。但可以使用PHP。

提前致谢

1 个答案:

答案 0 :(得分:2)

可以有更优雅的解决方案,但这个应该有效:

SELECT DATE_FORMAT( Joined, '%m/%Y' ) AS
    MONTH , team, (
    count( id ) / (
    SELECT count( * )
    FROM tablex
    WHERE DATE_FORMAT( Joined, '%m/%Y' ) = DATE_FORMAT( tx.Joined, '%m/%Y' )
    GROUP BY DATE_FORMAT( Joined, '%m/%Y' ) ) *100
    ) AS percentage
    FROM `tablex` AS tx
    GROUP BY DATE_FORMAT( Joined, '%m/%Y' ) , team