SQL命令检索列表嵌套在列中

时间:2017-02-10 17:04:58

标签: sql-server select nested

考虑下表:

Employees   Segment     Function    
John        Retail      Sales
Peter       Retail      Sales
Lucas       Retail      Sales
Steve       Retail      Sales
Maria       Retail      Sales

我想要一个列表,如下所示:(第一列的别名)

'Area'  'Employees'
Retail  John,Lucas,Maria
Sales   John,Lucas,Maria

要组装查询,我只有Employees列表。所以情况应该是这样的,例如:

WHERE Employees IN('John','Maria','Lucas').

我只能查询数据库。

我可以将Employees列表连续安装,如下所示:

SELECT 
Employees = Stuff(
  (SELECT N', ' + Employees FROM table A WHERE Employees
        IN('John','Maria','Lucas') FOR XML PATH(''),TYPE)
  .value('text()[1]','nvarchar(max)'),1,2,N'');

我可以创建'区域'通过合并Segment和Function,如下所示:

SELECT Segment 'Area' FROM table
WHERE Employees IN('John','Maria','Lucas')
UNION SELECT Function 'Area' FROM table
WHERE Employees IN('John','Maria','Lucas')

我想将这两个选项合并为UNION,如下所示:

SELECT 
    Employees = Stuff(
      (SELECT N', ' + Employees FROM table A WHERE Employees
            IN('John','Maria','Lucas') FOR XML PATH(''),TYPE)
      .value('text()[1]','nvarchar(max)'),1,2,N'')
    UNION
    SELECT Segment 'Area' FROM table
    WHERE Employees IN('John','Maria','Lucas')
    UNION SELECT Function 'Area' FROM table
    WHERE Employees IN('John','Maria','Lucas')

结果出来了,如:

'Employees'
John,Maria,Lucas
Retail
Sales

也许我错过了UNION语法的一些细节,或者它并不像我预期的那么简单。

2 个答案:

答案 0 :(得分:0)

你仍然可以使用你的UNION,你只需要做两次STUFF()。

SELECT DISTINCT Segment AS 'Area'
                , Stuff((SELECT N', ' + Employees 
                        FROM table A 
                        WHERE Employees IN('John','Maria','Lucas') 
                        FOR XML PATH(''),TYPE).value('text()[1]','nvarchar(max)'),1,2,N'') FROM table
WHERE Employees IN ('John','Maria','Lucas')
UNION
SELECT DISTINCT Func AS 'Area'
            , Stuff((SELECT N', ' + Employees 
                    FROM table A 
                    WHERE Employees IN('John','Maria','Lucas') 
                    FOR XML PATH(''),TYPE).value('text()[1]','nvarchar(max)'),1,2,N'') FROM table
WHERE Employees IN ('John','Maria','Lucas')

答案 1 :(得分:0)

希望,这将满足您的要求。

在sqlfiddle上尝试过,工作正常。

SELECT  a.Fun Area, 
        SUBSTRING(d.Employees,1, LEN(d.Employees) - 1) Employees
FROM( SELECT DISTINCT Fun FROM test_so) a
        CROSS APPLY
        (SELECT [Employees] + ', ' FROM test_so AS B WHERE A.Fun = B.Fun FOR XML PATH('')
        ) D (Employees)     
UNION
SELECT  a.Segment Area, SUBSTRING(d.Employees,1, LEN(d.Employees) - 1) Employees
FROM( SELECT DISTINCT Segment FROM test_so) a
        CROSS APPLY
        ( SELECT [Employees] + ', ' FROM test_so AS B WHERE A.Segment = B.Segment FOR XML PATH('')
        ) D (Employees) 

enter image description here