SQL垂直表到水平查询

时间:2018-03-01 18:09:09

标签: sql sql-server tsql

所以我有一张桌子,其中包含分配给桌面的多名员工。我需要帮助找出一种方法来展示员工的所有办公桌。

目前,我正在使用这个看起来很接近的查询,但它正拉着每一张桌子。

我希望它看起来像这样:

|fk_employee| fk_desk  |
|3          | 1000,1001|

使用SQL 2012

select fk_employee,
    stuff((SELECT distinct ', ' + cast(fk_desk as varchar(10))
    from dat_desk_employee e
    where e.fk_employee = e.fk_employee
    FOR XML PATH('')),1,1,'')
from dat_desk_employee e
group by fk_employee
order by fk_employee asc 

enter image description here

2 个答案:

答案 0 :(得分:0)

您对main,stuff查询使用了相同的别名。

create table dat_desk_employee (fk_desk int, fk_employee int);
insert into dat_desk_employee values
(1000, 2),(1000, 10),(1000, 23),(1000, 34),(1000, 55),
(1001, 3),(1001, 10),(1001, 23),(1001, 35),(1001, 60);
GO
10 rows affected
select fk_employee,
       stuff((SELECT distinct ', ' + cast(fk_desk as varchar(10))
              from dat_desk_employee t
              where t.fk_employee = e.fk_employee
       FOR XML PATH('')),1,1,'') fk_desks
from dat_desk_employee e
group by fk_employee
order by fk_employee asc 
GO
fk_employee | fk_desks   
----------: | :----------
          2 |  1000      
          3 |  1001      
         10 |  1000, 1001
         23 |  1000, 1001
         34 |  1000      
         35 |  1001      
         55 |  1000      
         60 |  1001      

dbfiddle here

答案 1 :(得分:0)

你可以试试这个

DECLARE @Table TABLE (fk_desk VARCHAR(100), fk_employee VARCHAR(100))

INSERT INTO @Table VALUES ('1000', '1')
INSERT INTO @Table VALUES ('1001', '1')
INSERT INTO @Table VALUES ('1000', '2')
INSERT INTO @Table VALUES ('1001', '2')
INSERT INTO @Table VALUES ('1002', '2')
INSERT INTO @Table VALUES ('1003', '3')

SELECT 
    fk_employee
    , STUFF((
          SELECT ',' + T.fk_desk
          FROM @Table T WHERE A.fk_employee = T.fk_employee
          FOR XML PATH('')), 1, 1, '') as fk_desk
FROM @Table A
GROUP BY A.fk_employee

之前已经回答过这个问题: How to make a query with group_concat in sql server