100分请求一条如何写SQL语句
原在access别人这样写:transform sum(quantity) as quantity select color from table1 group by color pivot invert(size)
目的:在原数据库中数据是这样
size color quantity
1 blue
问题点数:100、回复次数:8Top
1 楼dairy1(jonth1)回复于 2003-12-03 11:52:17 得分 0
原在access别人这样写:transform sum(quantity) as quantity select color from table1 group by color pivot invert(size)
目的:在原数据库中数据是这样
size color quantity
1 blue 1
1 red 2
2 black 2
1 black 4
数据有重复的,要累计
要达到输出是这样的表
size-> 1 2
black 4 2
blue 1
red 2Top
2 楼dairy1(jonth1)回复于 2003-12-03 11:54:25 得分 0
第一次没写完。
最终表是以size为行,color为列,当中的数字是经过统计的。如何用sql写在sql server中实现啊Top
3 楼TechnoFantasy((VB MVP)www.applevb.com)回复于 2003-12-03 12:03:13 得分 50
http://expert.csdn.net/Expert/topic/2097/2097186.xmlTop
4 楼TechnoFantasy((VB MVP)www.applevb.com)回复于 2003-12-03 12:03:59 得分 0
http://expert.csdn.net/Expert/topic/2116/2116990.xmlTop
5 楼yoki(小马哥--鬓微霜,又何妨)回复于 2003-12-03 12:29:36 得分 0
select size,color,sum(quantity) as quantity
from 表
group by size,colorTop
6 楼dairy1(jonth1)回复于 2003-12-03 14:49:01 得分 0
上述旋转结果可以使用,但是当列值不固定而要旋转如何处理?
即象解答例子中,当quarter可以取不止1-4的值,不固定应该如何处理
Top
7 楼yoki(小马哥--鬓微霜,又何妨)回复于 2003-12-03 16:44:20 得分 50
--测试如下:
create table ztable(项目 int, 日期 varchar(10),单号 int,品名 varchar(50),数量 int)
insert into ztable select 1,'4-9' ,18, '電板', 1500
insert into ztable select 2,'4-10',8 , '模組', 900
insert into ztable select 3,'4-11',18, '模組', 1500
insert into ztable select 4,'4-14',17, '電板', 1500
declare @sql varchar(8000)
set @sql='select 项目,日期,单号'
select @sql = @sql + ',sum(case 品名 when '''+品名+''' then 数量 else 0 end) as '+品名
from (select distinct 品名 from ztable) as a
select @sql = @sql+' from ztable group by 项目,日期,单号'
exec(@sql)
drop table ztable
-- 结果如下:
-- 项目 日期 单号 電板 模組
-- ----------- ---------- ----------- ----------- -----------
-- 1 4-9 18 1500 0
-- 2 4-10 18 0 900
-- 3 4-11 18 0 1500
-- 4 4-14 17 1500 0Top
8 楼yoki(小马哥--鬓微霜,又何妨)回复于 2003-12-03 16:48:11 得分 0
再给你一个例子:
declare @ table(department nvarchar(50), goodsname nvarchar(50),quantity int)
insert into @ values('部门M' , '货品A' , '100')
insert into @ values('部门M' , '货品B' , '3000')
insert into @ values('部门N' , '货品C' , '5')
insert into @ values('部门N' , '货品B' , '200')
要得到结果:
department 货品A 货品B 货品C
------------- ---------- --------- ---------
部门M 100 3000 0
部门N 0 200 5
select * into temp from @
declare @sql varchar(8000)
set @sql = 'select department'
select @sql = @sql + ',sum(case goodsname when '''+goodsname+''' then quantity else 0 end) as '+goodsname
from (select distinct goodsname from temp) as a
select @sql = @sql+' from temp group by department'
exec(@sql)
drop table tempTop




