2013-07-08 46 views
0

在組嵌套查詢我有一個表中的一些數據調用SQL Server的「測試」:SQL通過

ID Name Department 
1 Person1 IT 
2 Person2 Finance 
3 Person3 IT 
4 Person4 IT 
5 Person5 Finance 

的SQL我使用的查詢是:

SELECT Department AS '@Department', 
(
    SELECT Name 
    FROM testing 
    WHERE Department = Department 
    FOR XML PATH ('Person'), TYPE 
) 
FROM testing 
GROUP BY Department 
FOR XML PATH ('Department'), TYPE 

現在的問題是輸出不按部門分組。相反,所有人都被納入財務部門,再次被納入IT部門。

我在哪裏錯了?

在此先感謝


的電流輸出爲:

<Department Department="Finance"> 
    <Person> 
    <Name>Person1</Name> 
    </Person> 
    <Person> 
    <Name>Person2</Name> 
    </Person> 
    <Person> 
    <Name>Person3</Name> 
    </Person> 
    <Person> 
    <Name>Person4</Name> 
    </Person> 
    <Person> 
    <Name>Person5</Name> 
    </Person> 
</Department> 
<Department Department="IT"> 
    <Person> 
    <Name>Person1</Name> 
    </Person> 
    <Person> 
    <Name>Person2</Name> 
    </Person> 
    <Person> 
    <Name>Person3</Name> 
    </Person> 
    <Person> 
    <Name>Person4</Name> 
    </Person> 
    <Person> 
    <Name>Person5</Name> 
    </Person> 
</Department> 

但我需要的輸出是:

<Department Department="Finance"> 
    <Person> 
    <Name>Person2</Name> 
    </Person> 
    <Person> 
    <Name>Person5</Name> 
    </Person> 
</Department> 
<Department Department="IT"> 
    <Person> 
    <Name>Person1</Name> 
    </Person> 
    <Person> 
    <Name>Person3</Name> 
    </Person> 
    <Person> 
    <Name>Person4</Name> 
    </Person> 
</Department> 

回答

1

你需要,因爲你有兩個引用使用別名testing表格:

SELECT Department AS '@Department', 
(
    SELECT Name 
    FROM testing t2 
    WHERE t2.Department = t.Department 
    FOR XML PATH ('Person'), TYPE 
) 
FROM testing t 
GROUP BY Department 
FOR XML PATH ('Department'), TYPE 

您的查詢有Department = Department。這兩個參考內部testing,所以他們只選擇部門的非NULL值。

+0

該死!我是一個白癡 :) – user2483744