易截截图软件、单文件、免安装、纯绿色、仅160KB

sql行转列


写一个存储过程,将表一按照表二的形式进行查询。
仓库名称 商品名称 数量
A
S001 12
A S002 17
A
S003 10
B S001 21
B
S002 5
B S003 0

C S001 100
C S002 11
C S003 25
(表一)

品名称 总库存 A B C
S001 133 12 21 100
S002 33 17 5 11
S003 35 10 0
25
(表二)
create

table
tb(仓库名称
varchar
(
10
),商品名称
varchar
(
10
),数量
int
)
insert

into
tb
values
(
'
A
'
,
'
S001
'
,
12
)
insert

into
tb
values
(
'
A
'
,
'
S002
'
,
17
)
insert

into
tb
values
(
'
A
'
,
'
S003
'
,
10
)
insert

into
tb
values
(
'
B
'
,
'
S001
'
,
21
)
insert

into
tb
values
(
'
B
'
,
'
S002
'
,
5
)
insert

into
tb
values
(
'
B
'
,
'
S003
'
,
0
)
insert

into
tb
values
(
'
C
'
,
'
S001
'
,
100
)
insert

into
tb
values
(
'
C
'
,
'
S002
'
,
11
)
insert

into
tb
values
(
'
C
'
,
'
S003
'
,
25
)
go
--
如果只有A,B,C,则使用静态SQL。
select
商品名称,

sum
(数量) 总库存,

sum
(
case
仓库名称
when

'
A
'

then
数量
else

0

end
)
[
A
]
,

sum
(
case
仓库名称
when

'
B
'

then
数量
else

0

end
)
[
B
]
,

sum
(
case
仓库名称
when

'
C
'

then
数量
else

0

end
)
[
C
]
from
tb
group

by
商品名称
/*
商品名称 总库存 A B C
---------- ----------- ----------- ----------- -----------
S001 133 12 21 100
S002 33


相关文档:

Sql2005/08 表结构 SQL 语句

SELECT
(case when a.colorder=1 then d.name
--+'('+cast(h.value as nvarchar)+')'
else '' end)表名,
a.colorder 字段序号,
a.name 字段名,
isnull(g.[value],'') AS 字段说明,
(case when COLUMNPROPERTY( a.id,a.name,'IsIdentity')=1 then '√'else '' end) 标识,
(case whe ......

SQL Server 管理常用的SQL和T SQL

1. 查看数据库的版本  
  select @@version
 
  常见的几种SQL SERVER打补丁后的版本号:
 
  8.00.194   Microsoft SQL Server 2000
  8.00.384   Microsoft SQL Server 2000 SP1
  8.00.532   Microsoft SQL Server 2000 SP2
  8.00.760 &nb ......

实现多行合并一行的SQL写法

[ORACLE]
项目中遇到一个需求,需要将多行合并为一行。
表结构如下:
NAME                            Null           ......

sql:存储过程,事务,out参数

CREATE proc [dbo].[proc_DeleteTemplet] (@templeId varchar(15),@errorMessage varchar(50) output)
as
begin
  declare @error int
  set @error =0
  begin tran
  delete from tc_templet_Head where fBillNo=@templeId
  set @error=@error+@@error
  delete from tc_templet_ ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号