gpt4 book ai didi

sql-server - 根据值将SQL列拆分为多个列

转载 作者:行者123 更新时间:2023-12-05 05:16:04 25 4
gpt4 key购买 nike

我有一个像下面这样的表格

Opp_ID     Role_Name     Role_User_Name
---------------------------------------
1 Lead Person_one
1 Developer Person_two
1 Developer Person_three
1 Owner Person_four
1 Developer Person_five

我现在需要根据值将 Role_Name 列拆分为 3 个不同的列。我需要确保没有 NULL 值,所以表格应该如下所示

Opp_ID     Lead        Developer     Owner
--------------------------------------------------
1 Person_one Person_two Person_four
1 Person_one Person_three Person_four
1 Person_one Person_five Person_four

我的代码目前是:

SELECT
ID,
CASE WHEN Role_Name = 'Lead' THEN Role_User_Name ELSE NULL END AS Lead,
CASE WHEN Role_Name = 'Developer' THEN Role_User_Name ELSE NULL END AS Developer,
CASE WHEN Role_Name = 'Owner' THEN Role_User_Name ELSE NULL END AS Owner
FROM
[table1]
WHERE
Role_Name IN ('Lead','Developer','Owner')

不幸的是,这会返回这些结果:

Opp_ID     Lead        Developer     Owner
-------------------------------------------
1 Person_one NULL NULL
1 NULL Person_two NULL
1 NULL Person_three NULL
1 NULL NULL Person_four
1 NULL Person_five NULL

我假设要让它正常工作,您需要将代码重新加入自身,但我似乎无法让它正常工作。

最佳答案

要为每个开发人员申请一个 Opp_ID 并引导您的所有者,您需要如下内容:

SELECT o.opp_id
, o.Role_User_Name AS Owner
, l.Role_User_Name AS Lead
, d.Role_User_Name AS Developer
FROM t1 AS o
LEFT OUTER JOIN t1 l ON o.opp_id = l.opp_id AND l.Role_Name = 'Lead'
LEFT OUTER JOIN t1 d ON o.opp_id = d.opp_id AND d.Role_Name = 'Developer'
WHERE o.Role_Name = 'Owner'

https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=da4daea062534245bed474f93ffafbb7

关于sql-server - 根据值将SQL列拆分为多个列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50911383/

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