SQL Server:如何将多个行值分组到单独的列中?

时间:2017-07-31 18:23:19

标签: sql sql-server

我正在尝试创建SELECT查询,这样我就可以将联系人的多个电话号码合并到不同的列中。

例如,我想要以下

Email  |  Phone  |  ID  |
------------------------|
x@x.com| 555-5555| 001  |
x@x.com| 555-5556| 001  |

代替:

Email  |  Phone  |  Phone2  | Phone3 |  ID  |
--------------------------------------------|
x@x.com| 555-5555| 555-5556 |  NULL  | 001  |

虽然这可能是不好的做法,但严格来说,我可以将结果导出为CSV,以便将数据上传到CRM系统,导入时不允许任何重复。我看了一遍,似乎无法找到一个处理电话号码的答案,因为MINMAX只允许两个而不是更多。

最复杂的部分是数据库的结构,很可能涉及复杂的查询。这是我到目前为止尝试的但是只能得到2个数字,我需要剩下的列(请记住,我不是SQL人员):

SELECT DISTINCT
       C.CONTACTID,
       MAX(T.NUMBERVALUE) AS Phone1,
       MIN(T.numbervalue) AS Phone2
FROM TBL_PHONE T
     JOIN TBL_CONTACT C ON C.CONTACTID = T.CONTACTID
     JOIN TBL_EMAIL E ON E.CONTACTID = C.CONTACTID
WHERE T.NUMBERVALUE IS NOT NULL
      AND LEN(T.NUMBERVALUE) > 0
GROUP BY C.CONTACTID;

1 个答案:

答案 0 :(得分:2)

这是一种动态的支点方式:

declare @table table (Email varchar(64), Phone varchar(16), ID varchar(3))
insert into @table
values

('x@x.com','555-5555','001'),
('x@x.com','555-5556','001'),
('x@x.com','555-5557','001'),
('x@x.com','555-5558','001'),
('x@xdd.com','333-5556','002'),
('x@xdd.com','444-5556','002'),
('x@xdd.com','777-5556','002')


select
    Email
    ,Phone
    ,ID
    ,row_number() over (partition by ID order by Phone) as RN
into #staging
from 
    @table




DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)

--Get distinct values of the PIVOT Column 
SELECT @ColumnName= ISNULL(@ColumnName + ',','') 
       + QUOTENAME(RN)
FROM (SELECT DISTINCT RN FROM #staging) AS RN

--Prepare the PIVOT query using the dynamic 
SET @DynamicPivotQuery = 
  N'SELECT Email, ID, ' + @ColumnName + '
    FROM #staging
    PIVOT(MAX(Phone) 
          FOR RN IN (' + @ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery

drop table #staging

如果您只是期望3,正如您所述,您可以跳过动态...

declare @table table (Email varchar(64), Phone varchar(16), ID varchar(3))
insert into @table
values

('x@x.com','555-5555','001'),
('x@x.com','555-5556','001'),
('x@xdd.com','333-5556','002'),
('x@xdd.com','444-5556','002'),
('x@xdd.com','777-5556','002')

;with cte as(
select
    Email
    ,Phone
    ,ID
    ,row_number() over (partition by ID order by Phone) as RN
from 
    @table)

select
    Email
    ,max(case when RN = 1 then Phone end) as Phone1
    ,max(case when RN = 2 then Phone end) as Phone2
    ,max(case when RN = 3 then Phone end) as Phone3
    ,ID
from
    cte
group by
    Email
    ,ID