我有一个task
表,其中包含以下记录:
id | client_id | user_id | designation_id | total_hours
-----------------------------------------------------------------
1 | 14 | 134 | 1 | 4
2 | 14 | 135 | 2 | 1
3 | 15 | 136 | 3 | 3
4 | 16 | 137 | 4 | 4.5
和designation
表:
id | title
------------------------
1 | Cloud Analyst
2 | Data Analyst
3 | Data QA Analyst
4 | Project Manager
.
.
名称记录是动态的,因此我不想对其进行硬编码。
我正在尝试获得以下输出:
client | user | Cloud Analyst | Data Analyst | Data QA Analyst | Project Manager
-------------------------------------------------------------------------------------------
14 | 134 | 4 | | |
14 | 135 | | 1 | |
15 | 136 | | | 3 |
16 | 137 | | | | 4.5
换句话说:
columns
和client_id
表中的designation_id
列以外,还将所有可用的名称(来自名称表)列为task
。total_hours
值应放在相应的designation
列下,即,如果用户是cloud analyst
(根据designation_id),则他的hours
值应在{{1}以下}列。这是我尝试做的事情:
cloud analyst
如何获得输出?
答案 0 :(得分:0)
如果您需要数据透视,则可以使用几种情况(或如果使用)
SELECT t.client_id
, t.user_id
, case when t.designation_id = 1 then t.total_hours else null end `Cloud Analyst`
, case when t.designation_id = 2 then t.total_hours else null end `Data Analyst`
, case when t.designation_id = 3 then t.total_hours else null end `Data QA Analyst`
, case when t.designation_id = 4 then t.total_hours else null end `Project Manager`
from task t
order by client_id ASC
答案 1 :(得分:0)
SELECT t.client_id
, t.user_id
, d.title
, t.total_hours
FROM task t
JOIN designation d
ON d.id = t.designation_id;
+-----------+---------+-----------------+-------------+
| client_id | user_id | title | total_hours |
+-----------+---------+-----------------+-------------+
| 14 | 134 | Cloud Analyst | 4.00 |
| 14 | 135 | Data Analyst | 1.00 |
| 15 | 136 | Data QA Analyst | 3.00 |
| 16 | 137 | Project Manager | 4.50 |
+-----------+---------+-----------------+-------------+
此问题的其余部分最好在应用程序代码中解决