SQL如何将多行数据合并到一行
解决时间 2021-05-18 10:49
- 提问者网友:像風在裏
- 2021-05-18 05:51
如题,需要将员工的一年的工资表显示出来, 已通过表关系查询到员工每月的工资情况,现在需要对每个员工的工资进行合并到另外一张临时表中 每员工一条记录 记录了每月的工资,现在问题是 如何将已得到的工资记录 合并到另外一张表中去 见图
第二张表中的 1--12是对应每月的工资
现在我是通过存储过程来处理的 但是却不知道如果合并 望各位达人帮帮忙 附上存储过程
create proc GetuserPay
@sj char(4),@user varchar(20)
as
declare @uid varchar(30),@name varchar(50)
create table #tempuser(uid varchar(30),name varchar(50),sj datetime,pay decimal(9,2))
insert into #tempuser select distinct(g.username),u.usernames,riqi,pay
from GongZi g join user_user u on u.username=g.username where convert(varchar,riqi,120) like (Select Convert(Varchar(7),
'2008',120))+'%'
select * from #tempuser
create table #monthlist(uid varchar(30),m1 decimal(9,2),m2 decimal(9,2),m3 decimal(9,2),m4 decimal(9,2),m5 decimal(9,2),
m6 decimal(9,2),m7 decimal(9,2),m8 decimal(9,2),m9 decimal(9,2),m10 decimal(9,2),m11 decimal(9,2),m12 decimal(9,2))
go
最佳答案
- 五星知识达人网友:执傲
- 2021-05-18 06:34
declare @t table(name varchar(10), time varchar(20), pay int)
insert @t
select 'admin', '2010-01', 5 union all
select 'admin', '2010-02', 90 union all
select 'admin', '2010-03', 45 union all
select 'admin', '2010-04', 45 union all
select 'admin', '2010-05', 45 union all
select 'admin', '2010-06', 34 union all
select 'admin', '2010-07', 23 union all
select 'wx', '2010-04', 90 union all
select 'wx', '2010-09', 100 union all
select 'wx', '2010-12', 500
select name,
coalesce([2010-01], 0) as [1], coalesce([2010-02], 0) as [2],
coalesce([2010-03], 0) as [3], coalesce([2010-04], 0) as [4],
coalesce([2010-05], 0) as [5], coalesce([2010-06], 0) as [6],
coalesce([2010-07], 0) as [7], coalesce([2010-08], 0) as [8],
coalesce([2010-09], 0) as [9], coalesce([2010-10], 0) as [10],
coalesce([2010-11], 0) as [11], coalesce([2010-12], 0) as [12]
from
(select * from @t) as source
pivot
(
sum(pay) for time in
(
[2010-01], [2010-02], [2010-03], [2010-04],
[2010-05], [2010-06], [2010-07], [2010-08],
[2010-09], [2010-10], [2010-11], [2010-12]
)
) as pvt
用pivot可以做,不过有点死板
等吃过饭我帮你写个存储过程试试
我要举报
大家都在看
推荐资讯