当前位置:首页 » 编程语言 » sql怎么把纵表转换成横表的函数
扩展阅读
webinf下怎么引入js 2023-08-31 21:54:13
堡垒机怎么打开web 2023-08-31 21:54:11

sql怎么把纵表转换成横表的函数

发布时间: 2022-07-09 01:44:05

sql竖表数据批量插入到横表中 注意是要插入到表中,不单单是查询出来

declare @idx int,@colName varchar(50),@tableID int,@sql varhcar(2000)

select @tableID=id from sysobjects where name='横表名'
set @idx=1
set @colName='Marks'+convert(varchar,@idx)
while(if exists(select * from sysocolumns where id=@tableID and name=@colName))
begin
set sql='insert into 纵表 select stuno,stuname,‘+@colName+’from 横表'
exec(@sql)
set @idx=@idx+1
set @colName='Marks'+convert(varchar,@idx)
end
没有调试,直观的基本上就是这个写法,复杂点的你可以单独再建个要需读取的列名表,循环取列名拼SQL再执行。
或者再写的复杂点,循环用union拼接select的部分
以上是针对类似问题的通用方案,适合列很多的情况。

如果仅限于上边的例 子不做任何扩展,最死的写法就是
insert into 纵表
from select * from(select stuno,stuname,marks1 from 横表
union select stuno,stuname,marks2 from 横表
union select stuno,stuname,marks3 from 横表
)t

当然如果直接查询生成表,也可以用select ...into的写法

⑵ mysql 纵表转横表,高手请支招

你这个需要后台处理一下才可以,直接转换比较麻烦,效率也不高。因为你需要计算出每天的开始时间和结束时间insert into newtable select employeeID,days,MAX(cardTime) as endtime,Min(cardTime) as starttime from
table group by employeeID,days; 大概就这意思,自己在调试调试吧

⑶ SQL 如何查询时 竖着的数据 横着显示

你这个是将纵表转换为横表,例如如下数据:
'wangming', 'shuxue', 100
'wangming', 'yuwen', 90
'wangming', 'yingyu', 140

可以使用如下语句处理:
select a.v_name,a.v_score shuxue,b.v_score yuwen,c.v_score yingyu from temp_1 a,temp_1 b,temp_1 c
where a.v_name=b.v_name
and a.v_name=c.v_name
and a.v_name='wangming'
and a.v_course='shuxue'
and b.v_course='yuwen'
and c.v_course='yingyu';

⑷ sql怎么将纵向数据列表转化为横向数据字段

--行列互转
/******************************************************************************************************************************************************
以学生成绩为例子,比较形象易懂

整理人:中国风(Roy)

日期:2008.06.06
******************************************************************************************************************************************************/

--1、行互列
--> --> (Roy)生成测试数据

if not object_id('Class') is null
drop table Class
Go
Create table Class([Student] nvarchar(2),[Course] nvarchar(2),[Score] int)
Insert Class
select N'张三',N'语文',78 union all
select N'张三',N'数学',87 union all
select N'张三',N'英语',82 union all
select N'张三',N'物理',90 union all
select N'李四',N'语文',65 union all
select N'李四',N'数学',77 union all
select N'李四',N'英语',65 union all
select N'李四',N'物理',85
Go
--2000方法:
动态:

declare @s nvarchar(4000)
set @s=''
Select @s=@s+','+quotename([Course])+'=max(case when [Course]='+quotename([Course],'''')+' then [Score] else 0 end)'
from Class group by[Course]
exec('select [Student]'+@s+' from Class group by [Student]')

生成静态:

select
[Student],
[数学]=max(case when [Course]='数学' then [Score] else 0 end),
[物理]=max(case when [Course]='物理' then [Score] else 0 end),
[英语]=max(case when [Course]='英语' then [Score] else 0 end),
[语文]=max(case when [Course]='语文' then [Score] else 0 end)
from
Class
group by [Student]

GO
动态:

declare @s nvarchar(4000)
Select @s=isnull(@s+',','')+quotename([Course]) from Class group by[Course]
exec('select * from Class pivot (max([Score]) for [Course] in('+@s+'))b')

生成静态:
select *
from
Class
pivot
(max([Score]) for [Course] in([数学],[物理],[英语],[语文]))b

生成格式:
/*
Student 数学 物理 英语 语文
------- ----------- ----------- ----------- -----------
李四 77 85 65 65
张三 87 90 82 78

(2 行受影响)
*/

------------------------------------------------------------------------------------------
go
--加上总成绩(学科平均分)

--2000方法:
动态:

declare @s nvarchar(4000)
set @s=''
Select @s=@s+','+quotename([Course])+'=max(case when [Course]='+quotename([Course],'''')+' then [Score] else 0 end)'
from Class group by[Course]
exec('select [Student]'+@s+',[总成绩]=sum([Score]) from Class group by [Student]')--加多一列(学科平均分用avg([Score]))

生成动态:

select
[Student],
[数学]=max(case when [Course]='数学' then [Score] else 0 end),
[物理]=max(case when [Course]='物理' then [Score] else 0 end),
[英语]=max(case when [Course]='英语' then [Score] else 0 end),
[语文]=max(case when [Course]='语文' then [Score] else 0 end),
[总成绩]=sum([Score]) --加多一列(学科平均分用avg([Score]))
from
Class
group by [Student]

go

--2005方法:

动态:

declare @s nvarchar(4000)
Select @s=isnull(@s+',','')+quotename([Course]) from Class group by[Course] --isnull(@s+',','') 去掉字符串@s中第一个逗号
exec('select [Student],'+@s+',[总成绩] from (select *,[总成绩]=sum([Score])over(partition by [Student]) from Class) a
pivot (max([Score]) for [Course] in('+@s+'))b ')

生成静态:

select
[Student],[数学],[物理],[英语],[语文],[总成绩]
from
(select *,[总成绩]=sum([Score])over(partition by [Student]) from Class) a --平均分时用avg([Score])
pivot
(max([Score]) for [Course] in([数学],[物理],[英语],[语文]))b

生成格式:

/*
Student 数学 物理 英语 语文 总成绩
------- ----------- ----------- ----------- ----------- -----------
李四 77 85 65 65 292
张三 87 90 82 78 337

(2 行受影响)
*/

go

--2、列转行
--> --> (Roy)生成测试数据

if not object_id('Class') is null
drop table Class
Go
Create table Class([Student] nvarchar(2),[数学] int,[物理] int,[英语] int,[语文] int)
Insert Class
select N'李四',77,85,65,65 union all
select N'张三',87,90,82,78
Go

--2000:

动态:

declare @s nvarchar(4000)
select @s=isnull(@s+' union all ','')+'select [Student],[Course]='+quotename(Name,'''')--isnull(@s+' union all ','') 去掉字符串@s中第一个union all
+',[Score]='+quotename(Name)+' from Class'
from syscolumns where ID=object_id('Class') and Name not in('Student')--排除不转换的列
order by Colid
exec('select * from ('+@s+')t order by [Student],[Course]')--增加一个排序

生成静态:
select *
from (select [Student],[Course]='数学',[Score]=[数学] from Class union all
select [Student],[Course]='物理',[Score]=[物理] from Class union all
select [Student],[Course]='英语',[Score]=[英语] from Class union all
select [Student],[Course]='语文',[Score]=[语文] from Class)t
order by [Student],[Course]

go
--2005:

动态:

declare @s nvarchar(4000)
select @s=isnull(@s+',','')+quotename(Name)
from syscolumns where ID=object_id('Class') and Name not in('Student')
order by Colid
exec('select Student,[Course],[Score] from Class unpivot ([Score] for [Course] in('+@s+'))b')

go
select
Student,[Course],[Score]
from
Class
unpivot
([Score] for [Course] in([数学],[物理],[英语],[语文]))b

生成格式:
/*
Student Course Score
------- ------- -----------
李四 数学 77
李四 物理 85
李四 英语 65
李四 语文 65
张三 数学 87
张三 物理 90
张三 英语 82
张三 语文 78

(8 行受影响)
*/

⑸ sql 里面怎么把竖表变成横表

select 姓名,sum(case when 科目='数学' then 分数 end) as 数学,sum(case when 科目='语文' then 分数 end) as 语文,sum(case when 科目='英语' then 分数 end) as 英语 from 表名
group by 姓名

⑹ oracle sql 中 如何实现table的行列转换

你所谓的行列转换应该是指纵表转横表,横表转纵表.
给你个例子
纵表转横表:
使用DECODE语句,可以很方便的将纵表转为横表,例子如下:
原表查询结果:
ID MAJOR CURRENT_CREDITS
------ ---------------- ---------------
10000 Computer Science 98
10000 History 88
10001 Computer Science 75
10000 Economics 66
我们要把各科成绩从同一列转到不同的列中去。
SQL>?select id,
sum(decode(major,’Computer Science’,current_credits,0)) cs,
sum(decode(major,’History’,current_credits,0)) his,
sum(decode(major,’Economics’,current_credits,0)) eco
from students
group by id
ID CS HIS ECO
------ ----------- ------------- -----
10000 98 88 66
10001 75

横表转纵表:
使用 UNION 即可实现将横表转为纵表,以上面的表为例:
转换前:
ID CS HIS ECO
------ ----------- ------------- -----
10000 98 88 66
SQL>?select id, ’Computer Science’ major,cs current_credits
from students
union
select id, ’History’ major,his current_credits
from students
union
select id, ’Economics’ major,eco current_credits
from students
ID MAJOR CURRENT_CREDITS
------ ---------------- ---------------
10000 Computer Science 98
10000 History 88
10000 Economics 66

⑺ 如何通过sql将表中竖向数据转换成横向数据

行列转换等经典SQL语句

参考资料:http://blog.csdn.net/kiki113/archive/2009/04/24/4105929.aspx

1.--行列转换

原表: 姓名 科目 成绩
张三 语文 80
张三 数学 90
张三 物理 85
李四 语文 85
李四 物理 82
李四 英语 90
李四 政治 70
王五 英语 90

转换后的表: 姓名 数学 物理 英语 语文 政治
李四 0 82 90 85 70
王五 0 0 90 0 0
张三 90 85 0 80 0

实例:
create table cj --创建表cj
(
ID Int IDENTITY (1,1) not null, --创建列ID,并且每次新增一条记录就会加1
Name Varchar(50),
Subject Varchar(50),
Result Int,
primary key (ID) --定义ID为表cj的主键
);
--Truncate table cj
--Select * from cj
Insert into cj
Select '张三','语文',80 union all
Select '张三','数学',90 union all
Select '张三','物理',85 union all
Select '李四','语文',85 union all
Select '李四','物理',82 union all
Select '李四','英语',90 union all
Select '李四','政治',70 union all
Select '王五','英语',90
--行列转换
Declare @sql varchar(8000)
Set @sql = 'Select Name as 姓名'
Select @sql = @sql + ',sum(case Subject when '''+Subject+''' then Result else 0 end) ['+Subject+']'
from (select distinct Subject from cj) as cj --把所有唯一的科目的名称都列举出来
Select @sql = @sql+' from cj group by name'
Exec (@sql)

2. 行列转换--合并
原表: 班级 学号
1 1
1 2
1 3
2 1
2 2
3 1
转换后的表: 班级 学号
1 1,2,3
2 1,2
3 1

实例:
Create table ClassNo --创建表ClassNo
(
ID Int IDENTITY(1,1) not null, --创建列ID,并且每次新增一条记录就会加1
Class Varchar(50), --班级列
Number Varchar(50), --学号列
Primary Key(ID) --定义ID为表ClassNo的主键
);
--Truncate Table ClassNo
--Select * from ClassNo
Insert Into ClassNo
Select 1,1 Union all
Select 1,2 Union all
Select 1,3 Union all
Select 2,1 Union all
Select 2,2 Union all
Select 3,1

创建一个合并的函数
--Drop Function KFReturn
Create Function KFReturn(@Class Varchar(50))
Returns Varchar(8000)
as
Begin
Declare @str Varchar(8000)
Set @str = ''
Select @str = @str + cast(Number as Varchar(50)) + ',' from ClassNo Where Class = @Class
Set @str = SubString(@str,1,len(@str)-1)
Return(@str)
End

--调用自定义函数得到结果
Select Distinct Class,dbo.KFReturn(Class) From ClassNo

3:列转行
--Drop Table ColumnToRow
Create table ColumnToRow
(
ID Int IDENTITY(1,1) not null, --创建列ID,并且每次新增一条记录就会加1
a int,
b int,
c int,
d int,
e int,
f int,
g int,
h int,
Primary Key(ID) --定义ID为表ColumnToRow的主键
);
--Truncate Table ColumnToRow
--Select * from ColumnToRow
Insert Into ColumnToRow
Select 15,9,1,0,1,2,4,2 Union all
Select 22,34,44,5,6,7,8,7 Union all
Select 33,44,55,66,77,88,99,12

Declare @sql Varchar(8000)
Set @sql = ''
Select @sql = @sql + rtrim(name) + ' from ColumnToRow union all Select ' from SysColumns Where id = object_id('ColumnToRow')
Set @sql = SubString(@sql,1,len(@sql)-70)
--70的长度就是这个字符串'from ColumnToRow union all Select ID from ColumnToRow union all Select ',因为它会把ID这一列的值也算进去,所以要把它截掉
Exec ('Select ' + @sql + ' from ColumnToRow')

⑻ sql如何自动实现更新,竖表变横表,是要用触发器还是别的方法实现,具体代码如何写

先给你讲一下你说的横表变竖表,其实就是行列转换,我写个例子给你看看:

列转行

录入经营范围时候会遇到列传行的问题解决方案如下:

在temp1 表有一下字段内容:

⑼ sql server 纵表转横表

如果单纯是你如上数据的话这样:

创建表:

createtablet
(idint,
orderidint,
prfnoint,
prfidvarchar(10));


insertintotvalues(16385,171202,1,'FB065_1');
insertintotvalues(16385,171202,2,'FB065_06');
insertintotvalues(16385,171202,3,'FB065_06');
insertintotvalues(16385,171202,4,'FB065_06');

insertintotvalues(16386,171202,1,'FB065_1');
insertintotvalues(16386,171202,2,'FB065_06');
insertintotvalues(16386,171202,3,'FB065_06');
insertintotvalues(16386,171202,4,'FB065_06');

执行:

selectid,orderid,
max(casewhenprfno=1thenprfidend)prfid1,
max(casewhenprfno=2thenprfidend)prfid2,
max(casewhenprfno=3thenprfidend)prfid3,
max(casewhenprfno=4thenprfidend)prfid4
fromtgroupbyid,orderid

结果:

如果需求复杂的话,就要改别的方法了。

⑽ mysql纵表转横表

分两次进行不同的查询就可以实现了

  1. 先查出组员信息,比如组员数量、文章总数、评论总数等

  2. 再查出组长信息

  3. 两个查询一合并就可以了

SQL角本如下:

selecta.用户名组长,b.组员数量,b.文章总数,b.评论总数
from(select编号,用户名fromtable_namewhere角色='组长')a,--找组长信息
(select组长,
count(1)组员数量,
sum(文章)文章总数,
sum(评论)评论总数
fromtable_name
where组长isnotnull
groupby组长)b--找组员信息
wherea.编号=b.组长