gpt4 book ai didi

mysql - 如何在 MySQL 中使用 group by 和 pivot?

转载 作者:行者123 更新时间:2023-11-29 02:23:12 34 4
gpt4 key购买 nike

任何人都可以帮我将 2 个表分组并显示如下...

我的第一个表是:

user_id | department-----------------------1       | user1----------------------2       | user2----------------------

表 2 是:

reserve_id | user_id | reserve_status--------------------------------------    1      |     1   |        1--------------------------------------    2      |     1   |        1--------------------------------------    3      |     1   |        2--------------------------------------    4      |     2   |        2--------------------------------------    5      |     2   |        0--------------------------------------    6      |     2   |        1*reserve_status 0 uncheck, 1 = approve , 2 = disapproval

我想要这样的产品:

department | sumreserve | sumreservapprove | sumreserveunapprove | uncheck---------------------------------------------------------------------------- user1     |     3      |        2         |         1           |    0---------------------------------------------------------------------------- user2     |     3      |        1         |         1           |    1

抱歉英语不好

最佳答案

您需要一个枢轴解决方案。

演示:
假设 so_q27895250_usersso_q27895250_reserve 作为表名

mysql>
mysql> select u.department, count(r.reserve_status) as total_reserves,
-> count( case when r.reserve_status = 0
-> then r.reserve_status else null end ) as unchecked,
-> count( case when r.reserve_status = 1
-> then r.reserve_status else null end ) as approved,
-> count( case when r.reserve_status = 2
-> then r.reserve_status else null end ) as unapproved
-> from so_q27895250_reserve r
-> left join so_q27895250_users u
-> on r.user_id = u.user_id
-> group by r.user_id
-> ;
+------------+----------------+-----------+----------+------------+
| department | total_reserves | unchecked | approved | unapproved |
+------------+----------------+-----------+----------+------------+
| user1 | 3 | 0 | 2 | 1 |
| user2 | 3 | 1 | 1 | 1 |
+------------+----------------+-----------+----------+------------+
2 rows in set (0.00 sec)

关于mysql - 如何在 MySQL 中使用 group by 和 pivot?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27895250/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com