2011-08-29 28 views
1

我需要你的帮助。可悲的是,我不知道SQL以及C#(或大多数其他语言),我已经达到了这个查询的极限。这篇文章可能有点冗长,所以我提前道歉,但我想确保我包含所有必要的信息。MS SQL,分组,XML以及更多...需要这个查询的一些帮助

我的目标是创建一个查询,从SQL中选择数据,按照其中一列的子串值对其进行分组,并以XML格式输出。我非常接近,但我碰到了一堵墙。

这里有一个例子是什么应该样子:

<EXAMPLE_DATA> 
    <headEnd nam="AAAA"> 
    <hardware fromDevice="ExampleDeviceAAAA" /> 
    <hardware fromDevice="ExampleDeviceAAAA" /> 
    <hardware fromDevice="ExampleDeviceAAAA" /> 
    </headEnd> 
    <headEnd nam="BBBB"> 
    <hardware fromDevice="ExampleDeviceBBBB" /> 
    <hardware fromDevice="ExampleDeviceBBBB" /> 
    <hardware fromDevice="ExampleDeviceBBBB" /> 
</EXAMPLE_DATA> 

正如你所看到的,fromDevice的最后四个字符是什么定义我的头端分组......这里就是我米能够马上返回:

<EXAMPLE_DATA> 
    <headEnd nam="[headendId]"> 
    <hardware fromDevice="ExampleDeviceAAAA" headendId="AAAA" /> 
    <hardware fromDevice="ExampleDeviceAAAA" headendId="AAAA" /> 
    <hardware fromDevice="ExampleDeviceAAAA" headendId="AAAA" /> 
    <hardware fromDevice="ExampleDeviceBBBB" headendId="BBBB" /> 
    <hardware fromDevice="ExampleDeviceBBBB" headendId="BBBB" /> 
    <hardware fromDevice="ExampleDeviceBBBB" headendId="BBBB" /> 
</EXAMPLE_DATA> 

最后,这里是我有一个返回上面的XML代码:

SELECT 
    '[headendID]' as "@nam" 
    , (
    SELECT hardware.Name as "@fromDevice", RIGHT(hardware.Name, 4) as "@headendId" 
    FROM tblHardware AS hardware 
    GROUP BY RIGHT(hardware.Name, 4), hardware.Name 
    for xml path ('hardware') , type 
) 
for xml path ('headEnd'), root ('EXAMPLE_DATA') 

我已经删除了很多不必要的列以尝试使这篇文章更容易阅读。

那么,看看我需要什么样的XML,它甚至有可能吗?我想任何事情都是可能的......但在这种情况下,我完全被难住了。

感谢您的阅读!

编辑:为了确保我的问题是明确的,我需要的是SQL代码输出由硬件。名称的子字符串查询分组XML数据。我试图使输出看起来像上面的第一个XML块。

+0

是什么问题呢?您是否需要XML转换脚本或TSQL改变的脚本,或者您是否解决了您的问题? – Dalex

+0

查看前两个XML块......你会看到第一个XML块显示我的输出应该看起来像那个,而不是第二个。所以问题是,任何人都可以帮助我输出数据,使其看起来像第二个XML块? – SeanW

回答

1

在这里你去:

SELECT 
    RIGHT(categ.Name, 4) as "@nam" ,  
    (
    SELECT hardware.Name as "@fromDevice" 
    FROM tblHardware AS hardware 
    WHERE RIGHT(categ.Name, 4) = RIGHT(hardware.Name, 4) 
    for xml path ('hardware') , type 
    ) 
FROM tblHardware as categ 
GROUP BY RIGHT(categ.Name, 4) 
for xml path ('headEnd'), root ('EXAMPLE_DATA') 
+0

这很完美 - 非常感谢! – SeanW