关于SQL语句,把纪录变成字段横向显示

wysfair 2012-07-20 10:33:32


如上图

把Part表中的纪录按Class表变成字段显示..没有该个Class时显示False
每一个订单号显示一行纪录

是使用SQL语句好?,还是读到DataTable再操作好,

不知道SQL能否实现这个功能?
...全文
199 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
百年树人 2012-07-20
  • 打赏
  • 举报
回复
if object_id('[taborder]') is not null drop table [taborder]
go
create table [taborder]([预定号] int,[WBS] varchar(2))
insert [taborder]
select 1001,'E1' union all
select 1001,'E2' union all
select 1002,'E1'
GO
if object_id('[tabpart]') is not null drop table [tabpart]
go
create table [tabpart]([预定号] int,[WBS] varchar(2),[类别] varchar(6),[型号] varchar(2),[物号] int,[数量] int)
insert [tabpart]
select 1001,'E1','class1','A1',2000,1 union all
select 1001,'E1','class2','B1',2001,100 union all
select 1001,'E1','class3','C1',2002,1 union all
select 1001,'E2','class1','A1',2000,1 union all
select 1001,'E2','class2','B1',2001,100
GO
if object_id('[tabclass]') is not null drop table [tabclass]
go
create table [tabclass]([类别] varchar(6))
insert [tabclass]
select 'class1' union all
select 'class2' union all
select 'class3' union all
select 'class4'
GO

declare @sql varchar(8000)
select @sql=isnull(@sql+',','')
+'max(case when 类别='''+类别+''' then ''TRUE'' else ''FALSE'' end) as ['+类别+'],'
+'max(case when 类别='''+类别+''' then 型号 end) as ['+类别+'型号],'
+'max(case when 类别='''+类别+''' then 物号 end) as ['+类别+'物号],'
+'sum(case when 类别='''+类别+''' then 数量 end) as ['+类别+'数量]'
from tabclass
set @sql='select 预定号,WBS,'+@sql+' from tabpart group by 预定号,WBS'
exec (@sql)

/**
预定号 WBS class1 class1型号 class1物号 class1数量 class2 class2型号 class2物号 class2数量 class3 class3型号 class3物号 class3数量 class4 class4型号 class4物号 class4数量
----------- ---- ------ -------- ----------- ----------- ------ -------- ----------- ----------- ------ -------- ----------- ----------- ------ -------- ----------- -----------
1001 E1 TRUE A1 2000 1 TRUE B1 2001 100 TRUE C1 2002 1 FALSE NULL NULL NULL
1001 E2 TRUE A1 2000 1 TRUE B1 2001 100 FALSE NULL NULL NULL FALSE NULL NULL NULL

(2 行受影响)
**/
wysfair 2012-07-20
  • 打赏
  • 举报
回复

select @sql=isnull(@sql+',','')
+ 'max(case when partCatelog='''+ cast( catelogId as nvarchar)+''' then ''True'' else ''FALSE'' end) as ['+catelogName+'],'



搞定了..谢谢2L

结贴..
谢谢在CSDN每一个帮助大家的人~
wysfair 2012-07-20
  • 打赏
  • 举报
回复
2L,大神..问题已经基本解决

我但我考虑到,如果 那个tabclass是一个id与name的对应表...有没有更好的解决方法?

tabClass

类别ID 类别
-----------------
1 Class1
2 Class2


tabPart表中类别为类别ID

我这边先试下..2L大大可不可以再指点指点?



天-笑 2012-07-20
  • 打赏
  • 举报
回复
2楼 V5

22,210

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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