我有一张如下表:
cust no int id row no
111111 53453453623432 12345
111112 63453453623432 12346
111111 53453453623432 21234
111112 63453453623432 33347
我试图在下面获得以下结果 -
cust no int id row no 1 row no 2
111111 53453453623432 12345 21234
111112 63453453623432 12346 33347
我基本上试图以升序顺序转动行号。我会注意到特定客户可能会有无限量的ROW_NO'
我一直用这个拔出我的头发。不确定这是否需要tsql。任何帮助,将不胜感激。感谢大家。
答案 0 :(得分:1)
试试这个
select * from (
select cust_no,int_id,row_no,
'row_no_'+cast(row_number() over(partition by int_id
order by row_no) as nvarchar(10)) as colid
from @table) p
pivot (min(row_no) for colid in (row_no_1,row_no_2)) pvt
结果是
cust_no int_id row_no_1 row_no_2
111111 53453453623432 12345 21234
111112 63453453623432 12346 33347
下面的完整脚本,
declare @table table (
cust_no nvarchar(100), int_id nvarchar(100), row_no nvarchar(100) )
insert into @table
values('111111','53453453623432','12345')
,('111112','63453453623432','12346')
,('111111','53453453623432','21234')
,('111112','63453453623432','33347')
select * from (
select cust_no,int_id,row_no,
'row_no_'+cast(row_number() over(partition by int_id
order by row_no) as nvarchar(10)) as colid
from @table) p
pivot (min(row_no) for colid in (row_no_1,row_no_2)) pvt
答案 1 :(得分:0)
Declare @Query1 varchar(max),@Query2 varchar(max)
IF OBJECT_ID('tempdb..#Temp') IS NOT NULL
Drop TABLE #Temp
create table
#Temp ([cust_no] bigint,[int_id] bigint,[row_no] bigint)
Insert INTO #Temp([cust_no],[int_id],[row_no]) values (111111,53453453623432,12345)
Insert INTO #Temp([cust_no],[int_id],[row_no]) values (111112,63453453623432,12346)
Insert INTO #Temp([cust_no],[int_id],[row_no]) values (111111,53453453623432,21234)
Insert INTO #Temp([cust_no],[int_id],[row_no]) values (111112,63453453623432,33347)
Insert INTO #Temp([cust_no],[int_id],[row_no]) values (111111,53453453623432,33348)
Insert INTO #Temp([cust_no],[int_id],[row_no]) values (111111,53453453623432,33349)
IF OBJECT_ID('tempdb..#Temp1') IS NOT NULL
Drop TABLE #Temp1
select cust_no,int_id,row_no,
'row_no_'+cast(row_number() over(partition by int_id
order by row_no) as nvarchar(10)) as colid
INTO #Temp1 from #Temp
SELECT @Query1 = COALESCE(@Query1 + ', ', '') + colid
FROM #temp1 group by colid ;
--print @Query1
SET @Query2 = 'Select * from #temp1 pivot (min(row_no) for colid in (' + @Query1 + ' )) pvt'
--print @Query2
exec(@Query2)