我的数据表格式:(岗位不只3
日期 岗位 人员名称 ...
2008-1-1 GWA AAAAA
2008-1-1 GWB BBBBB
2008-1-1 GWC CCCCC
2008-1-2 GWA DDDDD
2008-1-2 GWB BBBBB
2008-1-2 GWC CCCCC
.
.
.
2008-1-30 ........ ...
现在我想查询每个月的排班表 查询输出的格式如下:
日期 岗位(GWA) GWB GWC
2008-1-1 AAAAA BBBB CCCCCC
请问各位高手该如何做? 谢谢指导
数据库是SQL server
日期 岗位 人员名称 ...
2008-1-1 GWA AAAAA
2008-1-1 GWB BBBBB
2008-1-1 GWC CCCCC
2008-1-2 GWA DDDDD
2008-1-2 GWB BBBBB
2008-1-2 GWC CCCCC
.
.
.
2008-1-30 ........ ...
现在我想查询每个月的排班表 查询输出的格式如下:
日期 岗位(GWA) GWB GWC
2008-1-1 AAAAA BBBB CCCCCC
请问各位高手该如何做? 谢谢指导
数据库是SQL server
*****************************************************************************
欢迎使用CSDN论坛专用阅读器 : CSDN Reader(附全部源代码)
http://feiyun0112.cnblogs.com/
岗位(GWB)=(case 岗位 when 'GWB' then 人员名称 end),
岗位(GWC)=(case 岗位 when 'GWC' then 人员名称 end)
from 数据表
order by 日期
declare @strSql as varchar(2000) ---声明一个字符串,用来连接sql语句
declare @strTepCol as varchar(10) ---获取不同的岗位名称
declare Unionsql cursor for select distinct fgangwei from A000001 for read only --建立游标来获取不同的岗位名称
begin
set @strSql='select fdate ' ---sql语句的前一部门
open Unionsql
while (0=0)
begin
fetch next from Unionsql into @strTepCol --取部门名称
if (@@fetch_status<>0) break
---下面开始组合sql语句
set @strSql=@strSql +',case fgangwei when ''' + @strTepCol+ ' '' then femp else null end as ['+@strTepCol+']'
endset @strSql=@strSql+' from A000001 ' --设置sql语句的最后一部门
execute(@strSql) ----执行sql语句
close Unionsql
deallocate Unionsql
end
go
按你的格式建立一张表A000001(fdate,fgangwei,femp) 然后按下面的代码执行,就可以达到你想要的效果,你可以将下面的代码建立一个存储过程
declare @strSql as varchar(2000) ---声明一个字符串,用来连接sql语句
declare @strTepCol as varchar(10) ---获取不同的岗位名称
declare Unionsql cursor for select distinct fgangwei from A000001 for read only --建立游标来获取不同的岗位名称
begin
set @strSql='select distinct fdate ' ---sql语句的前一部门
open Unionsql
while (0=0)
begin
fetch next from Unionsql into @strTepCol --取部门名称
if (@@fetch_status<>0) break
---下面开始组合sql语句,注意此处要用max函数,否则查询结果就不是你想要的,或者说是不理想的
set @strSql=@strSql +',max(case fgangwei when ''' + @strTepCol+ ' '' then femp else null end ) as ['+ @strTepCol+'] '
endset @strSql=@strSql+' from A000001 group by fdate' --设置sql语句的最后一部分
execute(@strSql) ----执行sql语句
close Unionsql
deallocate Unionsql
end
go