易截截图软件、单文件、免安装、纯绿色、仅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


相关文档:

SQL Server Mobile 学习(一):环境搭建

1.SQL Server Mobile 简介
2.获取 SQL Server Mobile
3.安装必备软件
4.安装开发环境
5.安装服务器环境
6.配置 Web 同步向导
7.使用 Internet Explorer 检查 SQL Server Mobile 服务器代理配置
8.使用SQL Server Mobile 数据库
==========================
1.SQL Server Mobile 简介
-------------------------- ......

实现多行合并一行的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_ ......

实现多行合并一行的SQL [MSSQL2005]写法

--1. 创建表,添加测试数据
CREATE TABLE tb(id int, [value] varchar(10))
INSERT tb SELECT 1, 'aa'
UNION ALL SELECT 1, 'bb'
UNION ALL SELECT 2, 'aaa'
UNION ALL SELECT 2, 'bbb'
UNION ALL SELECT 2, 'ccc'
--SELECT * from tb
/**//*
id value
----------- ----------
1 aa
1 bb
2 aaa ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号