2015-01-12 44 views
2

誰能幫我組2臺,並顯示如下圖所示...如何在MySQL中通過pivot來使用group?

我的第一個表是:

 
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 

對不起英語差

回答

2

您需要一個數據透視解決方案。

演示
假設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) 
+0

謝謝你的回答,你讓我的一天^ ^。 – Manioz