所以我有一个看起来像这样的表:
User_ID | Job_Func
--------------------
Adams | DEV
Adams | NET_ENG
Brice | QA
Cohen | DEV
Cohen | NET_ENG
Cohen | SUPERVISOR
它应该看起来像这样
UserName | Developer | NetworkEngineer | QA | Supervisor
-------------------------------------------------------------------------
Adams | 1 | 1 | 0 | 0
Brice | 0 | 0 | 1 | 0
Cohen | 1 | 1 | 0 | 1
我已经阅读了Pivots和动态Pivot,但是这个概念使我有些失望。我不需要在Job_Func上求和,而是将其放入每个用户只有一行的存储桶中,并吐出自定义列名。
我知道只需要列出4个工作职能(将来可能是5个)。
出于报告目的,最终会将其显示出来。
对此有任何帮助,或者只是向我指出正确的方向都是有用的。
答案 0 :(得分:2)
简便的方法是使用分组,求和和大小写-像这样:
SELECT UserName,
SUM(CASE WHEN Job_Func = 'DEV' THEN 1 ELSE 0 END) AS Developer,
SUM(CASE WHEN Job_Func = 'NET_ENG' THEN 1 ELSE 0 END) AS NetworkEngineer,
SUM(CASE WHEN Job_Func = 'QA' THEN 1 ELSE 0 END) AS QA,
SUM(CASE WHEN Job_Func = 'SUPERVISOR' THEN 1 ELSE 0 END) AS Supervisor
FROM TABLE_NAME
GROUP BY UserName
如果即使列出了一项以上的职务,即使您只希望1,也可以使用MAX代替SUM
答案 1 :(得分:0)
您可以使用ANSI方法来执行此操作,但是它有一些手动工作
SELECT DISTINCT
USER_ID,
(SELECT count(*) FROM TB1 WHERE TB1.JOB_FUNC = 'DEV' AND T.USER_ID = TB1.USER_ID) as Developer,
(SELECT count(*) FROM TB1 WHERE TB1.JOB_FUNC = 'NET_ENG' AND T.USER_ID = TB1.USER_ID) as NetworkEngineer,
(SELECT count(*) FROM TB1 WHERE TB1.JOB_FUNC = 'QA' AND T.USER_ID = TB1.USER_ID) as QA,
(SELECT count(*) FROM TB1 WHERE TB1.JOB_FUNC = 'SUPERVISOR' AND T.USER_ID = TB1.USER_ID) as supervisor
fROM TB1 T
或
SELECT USER_ID,
SUM(IFF(Job_Func = 'DEV', 1, 0)) AS Developer,
SUM(IFF(Job_Func = 'NET_ENG', 1, 0)) AS NetworkEngineer,
SUM(IFF(Job_Func = 'QA', 1, 0)) AS QA,
SUM(IFF(Job_Func = 'SUPERVISOR', 1, 0)) AS Supervisor
FROM TB1
GROUP BY USER_ID