行轉列不留空
select 'a' as [訂單號],'四川' as [位址] into #result
insert into #result
select 'a' as [訂單號],'成都' as [位址]
union all
select 'b' as [訂單號],'新疆' as [位址]
union all
select 'b' as [訂單號],'喀什' as [位址]
union all
select 'b' as [訂單號],'和田' as [位址]
select cast(row_number() over(partition by [訂單號] order by [位址]) as nvarchar(256)) as num,[訂單號],[位址] into #table from #result group by [訂單號],[位址]
declare @sql nvarchar(max)
set @sql = 'select [訂單號] '
select @sql = @sql + ' , max(case [num] when ''' + num + ''' then [位址] else '''' end) [位址]' from (select distinct num from #table) as a
set @sql = @sql + ' from #table group by [訂單號]'
行轉列,行做列頭
select 'a' as [訂單號],'四川' as [位址] into #result
insert into #result
select 'a' as [訂單號],'成都' as [位址]
union all
select 'b' as [訂單號],'新疆' as [位址]
union all
select 'b' as [訂單號],'喀什' as [位址]
union all
select 'b' as [訂單號],'和田' as [位址]
select * from #result
declare @sql nvarchar(max)
set @sql = 'select [訂單號] '
select @sql = @sql + ' , max(case [位址] when ''' + [位址] + ''' then [位址] else '''' end) ['+[位址]+']' from (select distinct [位址] from #result) as a
set @sql = @sql + ' from #result group by [訂單號]'
SQL實現行轉列
需求 用sql實現行轉列。如下圖所示 行顯示的資料轉換成列顯示 實現行轉列的sql指令碼如下 select date format last day date format now y m d y m d as 業務日期,max case index code when ind20101001 th...
SQL語句實現行轉列查詢
表sales 查詢結果如下 1 建表 create table dbo sales id int identity 1,1 not null,year int null,jidu int null,jine int null,primary key clustered id asc with pad...
mysql 查詢行轉列 SQL語句實現行轉列查詢
表sales 查詢結果如下 1 建表 create table dbo sales id int identity 1,1 not null,year int null,jidu int null,jine int null,primary key clustered id asc with pad...