SQL - 将值拆分为不同的列?

时间:2017-11-09 14:04:38

标签: sql sql-server-2012

我有一张看起来像这样的表

CAN | Contact1 | Contact 2 | Contact 3|  Email | Order Ref
22  | C1       |    C2     |    C3    |blah@b | 23334

我怎样才能将联系ID划分为3列,这样每个CAN只有1行?像

这样的东西
   server.bind('0.0.0.0:50051',grpc.ServerCredentials.createInsecure());

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

不知道为什么scimon会删除他的答案,但这是最终版本:

<强> SQL DEMO

with cte as(
select
    *
    ,row_number() over (partition by CAN order by Contact) as RN
from
    Table1)    
select
    CAN
    , MAX(case when RN = 1 then Contact end) as Contact1
    , MAX(case when RN = 2 then Contact end) as Contact2
    , MAX(case when RN = 3 then Contact end) as Contact3
    ,Email
    ,[Order Ref]
from
    cte
GROUP BY CAN, Email, [Order Ref] 

<强>输出

enter image description here

答案 1 :(得分:0)

以下是动态PIVOT运算符的示例:

create table #tbl(
    can int
    ,contact varchar(3)
    ,email varchar(10)
    ,orderRef int
)

insert into #tbl values (22, 'C1', 'blah@b', 23334)
insert into #tbl values (22, 'C2', 'blah@b', 23334)
insert into #tbl values (22, 'C3', 'blah@b', 23334)


declare @columnName as varchar(max)
declare @columnNameWAlias as varchar(max)
declare @sql as nvarchar(max)


SELECT @ColumnName = 
    ISNULL(@ColumnName + ',','') + QUOTENAME(contact)
    FROM (SELECT DISTINCT can, contact, email, orderRef FROM #tbl) AS Contacts

SELECT @columnNameWAlias = 
    ISNULL(@columnNameWAlias + ',','') + QUOTENAME(contact) + ' AS [Contact' + CAST(seq as varchar) + ']'
    FROM (SELECT DISTINCT can, contact, email, orderRef, seq = ROW_NUMBER() OVER (order by contact) FROM #tbl) AS Contacts


SET @sql = N'
    SELECT 
    CAN
    ,' + @columnNameWAlias + 
    ',Email
    ,orderREf
FROM (
    SELECT
        can
        ,contact
        ,Email
        ,orderRef
    FROM #tbl
) tbl
PIVOT (
    MAX(contact) FOR contact IN (' + @columnName + ')
) pvt
'

EXEC sp_executesql @sql;

drop table #tbl

Here您可以找到有关它的更多信息和示例。