【问题标题】:Split single row xml path result into multiple rows将单行 xml 路径结果拆分为多行
【发布时间】:2017-02-23 17:02:08
【问题描述】:

我在这里寻求一些指导。我有一个表,我需要的所有数据都混合在一个列(属性)中,如下所示:

Device Index     Attribute index     Attributes
      5               59              WS020121
      5               83              9C-B6-54-A0-41-40
      5               90              GROUP\darkwahm
      6               59              WS020122
      6               83              9D-B8-54-A0-50-40
      6               90              GROUP\darkperm

我要做的是将数据拆分为多列,以便显示为:

   Device              Mac Address              User
   WS020121            9C-B6-54-A0-41-40        GROUP\darkwahm 
   WS020122            9D-B8-54-A0-50-40        GROUP\darkperm            

经过一些研究,我被建议使用 XML 路径来获取这些结果,因此我创建了一个查询:

SELECT cast (av1.attributeValue as varchar(50)) + ','
   --cast( av1.attributeValue as varchar(50)) + ','
FROM [dbo].[DeviceAttributes] Av1 
WHERE av1.AttributeIndex=59 or av1.AttributeIndex=83 or av1.AttributeIndex=90
FOR XML PATH ('')

这在我的所有数据都在一起的意义上是有效的,但它在一行中都像这样:

WS022743,B0-5A-DA-B4-51-01;60-6D-C7-34-86-05,GROUP\darkwahm,WS022871,D0-27-  88-92-9B-8A,GROUP\securitypc,ABSE-PEARSOND,00-05-9A-3C-78-00;68-F7-28-92-0E-7A,GROUP\SlavinM

只是想知道我需要如何调整查询以将其拆分为多个列和行,就像我上面提到的那样。

【问题讨论】:

  • 你怎么知道9D-B8-54-A0-50-40Mac地址属于WS020122设备而不是WS020121
  • 抱歉,我忘记包含标识它们的设备索引列。我现在修改了我的 OP。

标签: sql for-xml-path


【解决方案1】:

因此,根据您的查询,数字:59, 83 and 90 是这些行的常量,如果是,您可以试试这个:

SELECT t1.Attributes as device,  t2.Attributes as  Mac_Address , t3.Attributes as "user"  from 
(SELECT Device_Index, Attributes  FROM [dbo].[DeviceAttributes] WHERE Attribute_index= 59) t1
INNER JOIN 
(SELECT Device_Index, Attributes  FROM [dbo].[DeviceAttributes] WHERE Attribute_index = 83) t2
ON t1.Device_Index = t2.Device_Index
INNER JOIN 
(SELECT Device_Index, Attributes  FROM [dbo].[DeviceAttributes] WHERE Attribute_index = 90) t3
ON t1.Device_Index = t3.Device_Index

【讨论】:

  • 这看起来成功了。非常感谢你:)
  • @AdamBriers - 如果对您有帮助,请接受答案;)
猜你喜欢
  • 1970-01-01
  • 2023-04-02
  • 2019-09-21
  • 2021-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多