Sql server 通过添加必要的列,将具有相同ID字段的多行合并为一行
下面是我正在使用的已存储在表中的内容Sql server 通过添加必要的列,将具有相同ID字段的多行合并为一行,sql-server,tsql,rows,Sql Server,Tsql,Rows,下面是我正在使用的已存储在表中的内容 ParentID ComputerName ProductCode -------- ------------ ------------ 117 AZ18LTDJBN2R1 EEADMIN_1000 117 AZ18LTDJBN2R1 EEGO____1000 117 AZ18LTDJBN2R1 EEPC 117 AZ18LTDJBN2R1 EPOAGENT3000 117 AZ18LTDJBN2R1 HOSTIPS_800
ParentID ComputerName ProductCode
-------- ------------ ------------
117 AZ18LTDJBN2R1 EEADMIN_1000
117 AZ18LTDJBN2R1 EEGO____1000
117 AZ18LTDJBN2R1 EEPC
117 AZ18LTDJBN2R1 EPOAGENT3000
117 AZ18LTDJBN2R1 HOSTIPS_8000
117 AZ18LTDJBN2R1 PCR_____1000
117 AZ18LTDJBN2R1 SITEADV_3500
117 AZ18LTDJBN2R1 SUPPCLNT1000
117 AZ18LTDJBN2R1 VIRUSCAN8800
如何将这9行合并为1行,并为每个记录/产品代码添加列
ParentID ComputerName EEADMIN EEGO EEPC EPOAgent etc.
-------- ------------ ------------ ------------- ------ ---------- ------
117 AZ18LTDJBN2R1 EEADMIN_1000 EEGO____1000 EEPC EPOAGENT3000 etc.
任何帮助都将不胜感激。谢谢。这里有一种方法:
select ParentId, ComputerName,
max(case when ProductCode like 'EEADMIN%' then ProductCode end) as EEAdmin,
max(case when ProductCode like 'EEGO%' then ProductCode end) as EEGO,
max(case when ProductCode like 'EEPC%' then ProductCode end) as EEPC,
. . .
from t
group by ParentId, ComputerName
您希望目标表的字段名的值存储在哪里
EEADMIN
,EEGO
,EEPC
,EPOAgent
?非常感谢您的帮助。实际上,我在一个嵌套查询中使用了您的想法,然后通过从中选择得到了正确的数据。再次感谢你的帮助。现在很好用。