求sql行转列的语句

cswuxiong110 2010-11-17 10:17:32
原数据:
id cNO type pct exp_id
1 80105 2 1.00 6
2 80105 3 1.00 7
3 80105 1 .50 8
4 80105 1 .50 9
6 80104 1 .50 8
7 80104 1 .50 9

转化后的数据:
cNO type1 pct1 exp_id1 type2 pct2 exp_id2 type3 pct3 exp_id3
80105 1 1.00(0.5+0.5) 8,9 2 1.00 6 3 1.00 7
80104 1 1.00(0.5+0.5) 8,9 null null null null null null

大侠们快快帮帮小弟吧。。。。。
...全文
63 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
cswuxiong110 2010-11-17
  • 打赏
  • 举报
回复
非常个写中国风的帮助
中国风 2010-11-17
  • 打赏
  • 举报
回复
SQL2005

DECLARE @s NVARCHAR(4000)
SET @s='select [cNO]'
Select
@s=@s+',[type'+RTRIM([type])+']=max(case when [type]='+RTRIM([type])+' then [type] end),[pct'
+RTRIM([type])+']=sum(case when [type]='+RTRIM([type])+' then [pct] else 0 end),[exp_id'
+RTRIM([type])+']=stuff((SELECT '',''+RTRIM([exp_id]) FROM TAB WHERE [cNO]=a.[cNO] AND [Type]='+RTRIM([type])+' for xml Path('''')),1,1,'''')'
from Tab GROUP BY [type]
PRINT @s
EXEC(@s+' from Tab as a group by [cNO] order by cNO desc')
中国风 2010-11-17
  • 打赏
  • 举报
回复
SQL2000需要用函數,SQL2005用XML

use Tempdb
go
--> -->

if not object_id(N'Tempdb..Tab') is null
drop table Tab
Go
Create table Tab([id] int,[cNO] int,[type] int,[pct] decimal(18,2),[exp_id] int)
Insert Tab
select 1,80105,2,1.00,6 union all
select 2,80105,3,1.00,7 union all
select 3,80105,1,.50,8 union all
select 4,80105,1,.50,9 union all
select 6,80104,1,.50,8 union all
select 7,80104,1,.50,9
Go
IF OBJECT_ID('F_str') IS NOT NULL
DROP FUNCTION F_str
go
CREATE FUNCTION F_str(@cNO INT,@Type INT)
RETURNS NVARCHAR(100)
AS
BEGIN
DECLARE @s NVARCHAR(100)
SET @s=''
SELECT @s=@s+','+RTRIM([exp_id]) FROM TAB WHERE Type=@Type AND [cNO]=@cNO
RETURN (STUFF(@s,1,1,''))
END
go
DECLARE @s NVARCHAR(4000)
SET @s='select [cNO]'
Select
@s=@s+',[type'+RTRIM([type])+']=max(case when [type]='+RTRIM([type])+' then [type] end),[pct'
+RTRIM([type])+']=sum(case when [type]='+RTRIM([type])+' then [pct] else 0 end),[exp_id'
+RTRIM([type])+']=dbo.F_str([cNO],'+RTRIM([type])+')'
from Tab GROUP BY [type]
PRINT @s
EXEC(@s+' from Tab group by [cNO] order by cNO desc')

/*
cNO type1 pct1 exp_id1 type2 pct2 exp_id2 type3 pct3 exp_id3
80105 1 1.00 8,9 2 1.00 6 3 1.00 7
80104 1 1.00 8,9 NULL 0.00 NULL NULL 0.00 NULL*/
-晴天 2010-11-17
  • 打赏
  • 举报
回复
这儿行转列的例子太多了,查查大乌龟的例程.

34,575

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧