mysql 两列分组的列数总和

发布于 2024-12-09 13:27:09 字数 737 浏览 0 评论 0原文

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(Joined, '%m/%Y'))。但可以使用PHP。

提前致谢

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');

output required is:

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

Please help me to do the above. Mostly preferred in MySQL (GROUP BY Team, DATE_FORMAT(Joined, '%m/%Y')). but can use PHP.

Thanks in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

天生の放荡 2024-12-16 13:27:09

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

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

There can be more elegant solutions but this one should work:

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文