Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 按ID的列到逗号分隔值分区_Sql Server_Sql Server 2008_Query Optimization - Fatal编程技术网

Sql server 按ID的列到逗号分隔值分区

Sql server 按ID的列到逗号分隔值分区,sql-server,sql-server-2008,query-optimization,Sql Server,Sql Server 2008,Query Optimization,我在SQLServer2008上有如下表 EmployeeCertificationHistoryId EmployeeCertificationID EmployeeID CertificationID CertificationDate 1 244 2192 1 2/15/2006 2 185 2058 87 4/10/2010 3 245 2240 102 8/11/2013 4 246 2249 104 11/23/2005 5 24

我在SQLServer2008上有如下表

 EmployeeCertificationHistoryId EmployeeCertificationID EmployeeID  CertificationID CertificationDate
1   244 2192    1   2/15/2006
2   185 2058    87  4/10/2010
3   245 2240    102 8/11/2013
4   246 2249    104 11/23/2005
5   247 2221    101 6/12/2013
6   248 2238    84  NULL
7   245 2240    102 8/11/2013
8   249 2240    102 8/4/2013
10  253 2175    84  6/19/2013
11  254 2239    105 2/5/2011
12  255 2239    111 11/22/2012
9   96  1468    92  12/6/2010
13  256 2239    110 11/22/2012
我需要用逗号分隔每个员工ID的certificationid。 例如,对于2239=>105111110

我已经编写了一个查询,但它在一列中给出了所有证书id。我的问题是

SELECT STUFF(
(SELECT ',' + CAST(C.CertificationID AS VARCHAR(100))
FROM tbl_PM_EmployeeCertificationMatrixHistory C
ORDER BY c.CertificationID
FOR XML PATH('')),1,1,'') AS CSV
GO

我只需要employeeid和certificationid。但我无法将其分类。

您只需将employeeid添加到查询中,并在其中添加
不同的

SELECT DISTINCT A.EmployeeID, STUFF(
(SELECT ',' + CAST(C.CertificationID AS VARCHAR(100))
FROM tbl_PM_EmployeeCertificationMatrixHistory C
WHERE C.EmployeeID = A.EmployeeID
ORDER BY c.CertificationID
FOR XML PATH('')),1,1,'') AS CSV
FROM tbl_PM_EmployeeCertificationMatrixHistory A
GO

如果要在CSV列表中仅返回
不同的
值,请在
排序依据
上方添加
分组依据c.CertificationID
,您需要相关子查询和员工列表。以下内容从同一个表中获取员工列表,但您可能有另一个包含此信息的表:

SELECT e.EmployeeID,
       STUFF((SELECT ',' + CAST(C.CertificationID AS VARCHAR(100))
              FROM tbl_PM_EmployeeCertificationMatrixHistory C
              where c.EmployeeID = e.EmployeeID
              ORDER BY c.CertificationID
              FOR XML PATH('')
             ),1, 1,'') AS CSV
from (select distinct EmployeeID
      from tbl_PM_EmployeeCertificationMatrixHistory
     ) e;

执行整个额外的
SELECT DISTINCT
子查询不是额外的处理吗?实际上,在外部查询中执行
DISTINCT
是额外的处理。这将首先为每个单独的员工生成不同的列表,然后生成子查询。将distinct放在外部可能会导致为表的每一行运行子查询,然后再执行distinct。这很有意义!我在发表评论后查看了执行计划,现在我看到了。谢谢