月份是查出来的,岗位也是查出来的,不固定
源数据格式
times postion bfb
2014-06 医生 75.00
2014-08 医生 17.00
2014-06 护士 60.00
2014-08 护士 75.00
2014-06 护工 20.00
2014-07 护士 60.00
2014-07 医生 75.00
2014-08 护工 100.00
2014-07 科室主任 100.00
2014-06 科室主任 100.00
2014-09 。。。 。。。。
需要转成如下格式
postion 2014-06 2014-07 2014-08 2014-09。。。
医生 75.00 75.00 17.00
护士 60.00 60.00 75.00
护工 20.00 0 100.00
科室主任 0 100.00 100.00
。。。。
------解决方案--------------------
----------------------------------------------------------------
-- Author :DBA_HuangZJ(發糞塗牆)
-- Date :2014-08-20 10:35:12
-- Version:
-- Microsoft SQL Server 2012 - 11.0.5058.0 (X64)
-- May 14 2014 18:34:29
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition: Core-based Licensing (64-bit) on Windows NT 6.3 <X64> (Build 9600: ) (Hypervisor)
--
----------------------------------------------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go
create table [huang]([times] varchar(7),[postion] varchar(8),[bfb] numeric(5,2))
insert [huang]
select '2014-06','医生',75.00 union all
select '2014-08','医生',17.00 union all
select '2014-06','护士',60.00 union all
select '2014-08','护士',75.00 union all
select '2014-06','护工',20.00 union all
select '2014-07','护士',60.00 union all
select '2014-07','医生',75.00 union all
select '2014-08','护工',100.00 union all
select '2014-07','科室主任',100.00 union all
select '2014-06','科室主任',100.00
--------------开始查询--------------------------
declare @s nvarchar(4000)
set @s=''
Select @s=@s+','+quotename([times])+'=max(case when [times]='+quotename([times],'''')+' then [bfb] else 0.0 end)'
from [huang] group by [times]
exec('select [postion]'+@s+' from [huang] group by [postion]')
----------------结果----------------------------
/*
postion 2014-06 2014-07 2014-08
-------- --------------------------------------- --------------------------------------- ---------------------------------------
护工 20.00 0.00 100.00
护士 60.00 60.00 75.00
科室主任 100.00 100.00 0.00
医生 75.00 75.00 17.00
*/
------解决方案--------------------
/*行列转换例子很多了,下面供参考
http://bbs.csdn.net/topics/390035109
name value