将多行中的值合并为一行,每个值在其自己的列中

时间:2019-07-31 11:06:00

标签: sql sql-server

我有许多网站可供客户注册,我想将所有网站上与电子邮件地址关联的所有客户ID合并为一行。我正在使用SQL Server。

示例源数据:

enter image description here

我想在新表中实现什么:

enter image description here

我的第一个想法是这样的,以电子邮件作为主键,但它不起作用。我可以使用CASE表达式吗?

SELECT c.[Email],
       (SELECT c.[CustomerID] FROM Customer c WHERE c.[BrandID] = '1859') AS [Brand1],
       (SELECT c.[CustomerID] FROM Customer c WHERE c.[BrandID] = '1594') AS [Brand2],
       (SELECT c.[CustomerID] FROM Customer c WHERE c.[BrandID] = '4578') AS [Brand3]
  FROM Customer c

3 个答案:

答案 0 :(得分:3)

只需使用条件聚合:

SELECT c.Email,
       MAX(CASE WHEN BrandID = 1859 THEN c.[CustomerID] END) as Brand1,
       MAX(CASE WHEN BrandID = 1594 THEN c.[CustomerID] END) as Brand2,
       MAX(CASE WHEN BrandID = 4578 THEN c.[CustomerID] END) as Brand3
FROM Customer c
GROUP BY c.Email;

BrandID看起来像一个数字,所以我删除了比较值周围的单引号。当然,如果确实是字符串,请使用单引号。

答案 1 :(得分:0)

您可以尝试这样的情况:

SELECT c.Email,
   SUM(CASE WHEN BrandID = 1859 THEN CustomerID ELSE 0 END) as Brand1,
   SUM(CASE WHEN BrandID = 1594 THEN CustomerID ELSE 0 END) as Brand2,
   SUM(CASE WHEN BrandID = 4578 THEN CustomerID ELSE 0 END) as Brand3
FROM Customer c
GROUP BY c.Email;

答案 2 :(得分:0)

您可以使用pivot

 ; with cte as (
 select row_number() over (partition by email order by brandid) as Slno,
 Email, brandid from table)
  , ct as (
  select brandid, 'brand' + cast(slno as varchar(5)) as Col, email from cte )
  select * from (
  select brandid, col, email from ct ) as d
  pivot (
  max(brandid) for col in ( [brand1], [brand2], [brand3] )
  ) as p