--一条语句就真的过分了,因为你的货位是动态的,这样写吧declare @s varchar(8000)
set @s=''
select @s=@s+',[库位'+商品库位+']=sum(case 商品库位 when '''+商品库位+''' then 库存数量 else 0 end)'
from 表
group by 商品库位
exec('select 商品ID,商品名'+@s+'
from 表
group by 商品ID,商品名')
set @s=''
select @s=@s+',[库位'+商品库位+']=sum(case 商品库位 when '''+商品库位+''' then 库存数量 else 0 end)'
from 表
group by 商品库位
exec('select 商品ID,商品名'+@s+'
from 表
group by 商品ID,商品名')
解决方案 »
- 急:求一条SQL语句?
- 怎样写把打竖的记录变成打横的记录,例子如下:
- 请教各位如何列出重复的记录
- phantomMan(我不吸烟,我讨厌别人吸烟) 大哥请进,感谢,特开帖子
- Excel导入数据库字段错误?
- SqlServer2000根据相同ID合并数据内容
- update大侠帮忙,简单更新update
- 本人昨天删除Sql server 2005 想用2008,但是在删除的时候可能误删了什么,结果重新安装出错了,求各位大神帮帮忙!
- 求SQL语句(在线等待)
- 关于删除出错的问题;(数据库编程 Visual C++ ADO)
- 我这个语句该怎么改?
- 在SQL查询中,如何在结果集中,计算一条记录具体重复多少次?
昏,一楼来了一个跟我一样笨的。HOHO
set @s=''
select @s=@s+',[库位'+商品库位+']=sum(case 商品库位 when '''+商品库位+''' then 库存数量 else 0 end)'
from 表
group by 商品库位
exec('select 商品ID,商品名'+@s+',合计=sum(库存数量)
from 表
group by 商品ID,商品名')
create table 表(商品ID char(3),商品名 varchar(10),商品库位 char(4),库存数量 int)
insert 表 select '001','冰箱','A001',3
union all select '002','电视','A001',3
union all select '003','空调','A001',3
union all select '001','冰箱','A002',3
union all select '001','冰箱','A003',3
go--查询
declare @s varchar(8000)
set @s=''
select @s=@s+',[库位'+商品库位+']=sum(case 商品库位 when '''+商品库位+''' then 库存数量 else 0 end)'
from 表
group by 商品库位
exec('select 商品ID,商品名'+@s+',合计=sum(库存数量)
from 表
group by 商品ID,商品名')
go--删除测试
drop table 表/*--测试结果商品ID 商品名 库位A001 库位A002 库位A003 合计
---- ---------- ----------- ----------- ----------- -----------
001 冰箱 3 3 3 9
002 电视 3 0 0 3
003 空调 3 0 0 3
--*/