行转列
CREATE TABLE T_ProductInitialDataTables
( [SerialNo] int NOT NULL IDENTITY (1, 1),
[ProductEnName] VARCHAR(128) NOT NULL,
[TableName] varchar(256) NOT NULL,
[FieldName] varchar(256) NOT NULL,
[FieleValue] varchar(max) NULL,
constraint PK_T_ProductInitialDataTables primary key ([SerialNo])
)
insert into T_ProductInitialDataTables ([ProductEnName],[TableName],[FieldName],
[FieleValue]) values
('ADMS20','AssessmentMemory','PointCode','网点号');
insert into T_ProductInitialDataTables ([ProductEnName],[TableName],[FieldName],
[FieleValue]) values
('ADMS20','AssessmentMemory','SerialNo','流水号');
insert into T_ProductInitialDataTables ([ProductEnName],[TableName],[FieldName],
[FieleValue]) values
('ADMS20','AssessmentMemory','Memory','备注');
insert into T_ProductInitialDataTables ([ProductEnName],[TableName],[FieldName],
[FieleValue]) values
('ADMS20','AssessmentMemory','PointCode','网点号');
insert into T_ProductInitialDataTables ([ProductEnName],[TableName],[FieldName],
[FieleValue]) values
('ADMS20','AssessmentMemory','SerialNo','流水号');
insert into T_ProductInitialDataTables ([ProductEnName],[TableName],[FieldName],
[FieleValue]) values
('ADMS20','AssessmentMemory','Memory','备注');
insert into T_ProductInitialDataTables ([ProductEnName],[TableName],[FieldName],
[FieleValue]) values
('ADMS20','AssessmentMemory','PointCode','网点号');
insert into T_ProductInitialDataTables ([ProductEnName],[TableName],[FieldName],
[FieleValue]) values
('ADMS20','AssessmentMemory','SerialNo','流水号');
insert into T_ProductInitialDataTables ([ProductEnName],[TableName],[FieldName],
[FieleValue]) values
('ADMS20','AssessmentMemory','Memory','备注');
GO
方法一:
declare @sql varchar(8000)
declare @cnt int
select @cnt = count(distinct FieldName) from T_ProductInitialDataTables group by productEnName,TableName
set @sql = 'select productEnName'
select @sql = @sql + ',max(case FieldName when ''' + FieldName + ''' then ''' + FIELEVALUE + ''' else '''' end)[' + FieldName + ']'
from (select distinct FieldName,FIELEVALUE from T_ProductInitialDataTables)t
select @sql = @sql + ' from T_ProductInitialDataTables group by productEnName,(SerialNo - 1)/' + ltrim(@cnt)
exec(@sql)
drop table T_ProductInitialDataTables
方法二:
select productEnName,
max(case FIELEVALUE when '网点号' then '网点号' else '' end) as PointCode,
max(case FIELEVALUE when '流水号' then '流水号' else '' end) as SerialNo,
max(case FIELEVALUE when '备注' then '备注' else '' end) as Memory
from @T_ProductInitialDataTables
group by productEnName
列转行
tableA
A B C
1 2 3
转为
tableB
A 1
B 2
C 3
方法:
select A from tableA
union
select B from tableA
union
select C from tableA