多表查询得到如下结果:编号 经营单位 货物名称 件数 重量 收费项目 收费金额
1 AAA 布 2 1000 搬运费 200
1 AAA 布 2 1000 运输费 300
1 AAA 布 2 1000 捆扎费 50
1 AAA 布 2 1000 材料费 30
1 AAA 布 2 1000 仓储费 100
1 AAA 布 2 1000 出库费 100
想变成:编号 业务资料名称 业务资料内容 收费项目 收费金额
1 经营单位 AAA 搬运费 200
1 货物名称 布 运输费 300
1 件数 2 捆扎费 50
1 重量 1000 材料费 30
1 仓储费 100
1 出库费 100
可以吗?
1 AAA 布 2 1000 搬运费 200
1 AAA 布 2 1000 运输费 300
1 AAA 布 2 1000 捆扎费 50
1 AAA 布 2 1000 材料费 30
1 AAA 布 2 1000 仓储费 100
1 AAA 布 2 1000 出库费 100
想变成:编号 业务资料名称 业务资料内容 收费项目 收费金额
1 经营单位 AAA 搬运费 200
1 货物名称 布 运输费 300
1 件数 2 捆扎费 50
1 重量 1000 材料费 30
1 仓储费 100
1 出库费 100
可以吗?
use ProduceManageSystem
go
if object_id(N'A',N'U') is not null drop table A
go
create table A
(
编号 int,
经营单位 nvarchar(100),
货物名称 nvarchar(200),
件数 int,
重量 int,
收费项目 nvarchar(100),
收费金额 int
)
go
insert into A
select 1 ,'AAA' ,'布', 2 ,1000,'搬运费', 200 union all
select 1 ,'AAA' ,'布', 2 ,1000,'运输费', 300 union all
select 1 ,'AAA' ,'布', 2 ,1000,'捆扎费', 50 union all
select 1 ,'AAA' ,'布', 2 ,1000,'材料费', 30 union all
select 1 ,'AAA' ,'布', 2 ,1000,'仓储费', 100 union all
select 1 ,'AAA' ,'布', 2 ,1000,'出库费', 100
go
with cte as
(
select
编号,
case when RN=1 then '经营单位'
when RN=2 then '货物名称'
when RN=3 then '件数'
when RN=4 then '重量'
when RN=5 then '仓储费'
when RN=6 then '出库费'
else '' end as 业务资料名称,
case when RN=1 then 经营单位
when RN=2 then 货物名称
when RN=3 then cast(件数 as nvarchar(10))
when RN=4 then cast(重量 as nvarchar(10))
when RN=5 then (select cast(收费金额 as nvarchar(10)) from A where 收费项目='仓储费' and 编号=1)
when RN=6 then (select cast(收费金额 as nvarchar(10)) from A where 收费项目='出库费' and 编号=1)
else '' end as 业务资料内容,
case when RN=1 then '搬运费'
when RN=2 then '运输费'
when RN=3 then '捆扎费'
when RN=4 then '材料费'
when RN=5 then ''
when RN=6 then ''
else '' end as 收费项目,
case when RN=1 then (select cast(收费金额 as nvarchar(10)) from A where 收费项目='搬运费' and 编号=1)
when RN=2 then (select cast(收费金额 as nvarchar(10)) from A where 收费项目='运输费' and 编号=1)
when RN=3 then (select cast(收费金额 as nvarchar(10)) from A where 收费项目='捆扎费' and 编号=1)
when RN=4 then (select cast(收费金额 as nvarchar(10)) from A where 收费项目='材料费' and 编号=1)
when RN=5 then ''
when RN=6 then ''
else '' end as 收费金额,
case when RN=1 then 1
when RN=2 then 2
when RN=3 then 3
when RN=4 then 4
when RN=5 then 5
when RN=6 then 6
else 0 end as 顺序from A,(select top 6 row_number()over(order by getdate()) as RN from sysobjects) B
)
select 编号,业务资料名称,业务资料内容,收费项目,收费金额 from cte
group by 编号,业务资料名称,业务资料内容,收费项目,收费金额,顺序
order by 顺序
drop table A(6 行受影响)
编号 业务资料名称 业务资料内容 收费项目 收费金额
----------- -------- ---------------------- ------ ----------
1 经营单位 AAA 搬运费 200
1 货物名称 布 运输费 300
1 件数 2 捆扎费 50
1 重量 1000 材料费 30
1 仓储费 100
1 出库费 100 (6 行受影响)