TSQL - 从ResultSet中删除重复项并将它们组合在一行中

时间:2012-02-01 12:45:12

标签: sql-server-2005 tsql

我有一个名为员工的表格,其中包含以下字段

Id | Name     | PrimaryEmail1  | PrimaryEmail2 | PrimaryEmail3
1  | JonSkeet | NULL           | NULL          | jonskeet@test.com
1  | JonSkeet | NULL           | Jon@test.com  | jonskeet@test.com
1  | JonSkeet | skeet@test.com | NULL          | jonskeet@test.com
2  | George   | G1@Test.com    | NULL          | NULL
2  | George   | NULL           | G2@test.com   | NULL
2  | George   | NULL           | NULL          | G3@test.com

如何编写TSQL查询以便我可以获得以下结果集?

Id | Name     | PrimaryEmail1  | PrimaryEmail2 | PrimaryEmail3
1  | JonSkeet | skeet@test.com | jon@test.com  | jonskeet@test.com
2  | George   | G1@test.com    | G2@test.com   | G3@test.com

2 个答案:

答案 0 :(得分:6)

MAX将消除NULL

SELECT
   ID, Name, 
   MAX(PrimaryEmail1) AS PrimaryEmail1,
   MAX(PrimaryEmail2) AS PrimaryEmail2, 
   MAX(PrimaryEmail3) AS PrimaryEmail3
FROM
   employee 
GROUP BY
   ID, Name

但是,您的JonSkeet示例显示PrimaryEmail3是相同的。您是否会期望每个ID +名称有不同的值?如果是这样,除非您选择MAX(或MIN偶数),否则不能合并为一行。

这假设Id-Name对也是一致的

答案 1 :(得分:0)

以下脚本将所有不同的非NULL电子邮件连接到一个列表中,分别针对每一列:

;
WITH employee (Id, Name, PrimaryEmail1, PrimaryEmail2, PrimaryEmail3) AS (
  SELECT 1, 'JonSkeet', NULL            , NULL          , 'jonskeet@test.com' UNION ALL
  SELECT 1, 'JonSkeet', NULL            , 'Jon@test.com', 'jonskeet@test.com' UNION ALL
  SELECT 1, 'JonSkeet', 'skeet@test.com', NULL          , 'jonskeet@test.com' UNION ALL
  SELECT 2, 'George'  , 'G1@Test.com'   , NULL          , NULL UNION ALL
  SELECT 2, 'George'  , NULL            , 'G2@test.com' , NULL UNION ALL
  SELECT 2, 'George'  , NULL            , NULL          , 'G3@test.com'
)

SELECT
  Id,
  Name,
  PrimaryEmail1 = SUBSTRING(
    (SELECT DISTINCT ', ' + PrimaryEmail1 FROM employee WHERE Id = e.Id FOR XML PATH ('')),
    3,
    999999
  ),
  PrimaryEmail2 = SUBSTRING(
    (SELECT DISTINCT ', ' + PrimaryEmail2 FROM employee WHERE Id = e.Id FOR XML PATH ('')),
    3,
    999999
  ),
  PrimaryEmail3 = SUBSTRING(
    (SELECT DISTINCT ', ' + PrimaryEmail3 FROM employee WHERE Id = e.Id FOR XML PATH ('')),
    3,
    999999
  )
FROM employee e
GROUP BY Id, Name

如果同一员工的三个PrimaryEmail列中的任何一列中永远不会有明显的非NULL值,您将获得与MINMAX相同的结果。否则,您将获得列表中的所有不同值

上述脚本的结果:

Id Name     PrimaryEmail1  PrimaryEmail2 PrimaryEmail3     
-- -------- -------------- ------------- ----------------- 
1  JonSkeet skeet@test.com Jon@test.com  jonskeet@test.com 
2  George   G1@Test.com    G2@test.com   G3@test.com