求一简单SQL语句!
有一表结构和内容如下:
货号 34码 35码 36码 37码 38码 39码 40码 总数
A 10 20 0 40 5 6 7 88
B 1 5 6 0 8 10 6 36
想通过查询得到如下结果
货号 尺码 数量
A 总数 118
A 34 10
A 35 20
A 37 40
A 38 5
A 39 6
A 40 7
B 总数 36
B 34 1
B 35 5
B 36 6
B 38 8
B 39 10
B 40 6
请高手指教,谢谢!
问题点数:50、回复次数:6Top
1 楼libin_ftsafe(子陌红尘:TS for Banking Card)回复于 2005-08-04 15:55:47 得分 15
select
a.货号,a.尺码,a.数量
from
(select 1 as level,货号,'总数' as 尺码,总数 as 数量 from 货号
union
select 2 as level,
union
select 2 as level,'34',34码 from 货号
union
select 2 as level,'35',35码 from 货号
union
select 2 as level,'36',36码 from 货号
union
select 2 as level,'37',37码 from 货号
union
select 2 as level,'38',38码 from 货号
union
select 2 as level,'39',39码 from 货号
union
select 2 as level,'40',40码 from 货号) a
order by
a.货号,a.level,a.尺码Top
2 楼wgqqgw(小强)回复于 2005-08-04 16:16:54 得分 5
觉得这个表结构怪怪的,万一哪天来了一批41、42码的鞋子呢?加列?Top
3 楼hsh_boy(逗号)回复于 2005-08-04 16:32:52 得分 0
有没有别的方法啊Top
4 楼coolingpipe(冷箫轻笛)回复于 2005-08-04 16:37:58 得分 15
我把libin_ftsafe(子陌红尘) 的答案修改一下
select
a.货号,a.尺码,a.数量
from
(select 货号,1 as level,'总数' as 尺码,总数 as 数量 from 表
union
select 货号,2 as level,'34',34码 from 表
union
select 货号,2 as level,'35',35码 from 表
union
select 货号,2 as level,'36',36码 from 表
union
select 货号,2 as level,'37',37码 from 表
union
select 货号,2 as level,'38',38码 from 表
union
select 货号,2 as level,'39',39码 from 表
union
select 货号,2 as level,'40',40码 from 表) a
order by
a.货号,a.level,a.尺码
Top
5 楼vivianfdlpw()回复于 2005-08-04 16:43:07 得分 15
--创建测试环境
create table A
(
[货号] varchar,
[34码] int,
[35码] int,
[36码] int,
[37码] int,
[38码] int,
[39码] int,
[40码] int,
[总数] int
)
insert A
select 'A',10,20,0,40,5,6,7,88 union
select 'B',1,5,6,0,8,10,6,36
--测试
select [货号],[尺码],[数量]
from
(
select A.ID,t.[货号],A.[尺码],B.[数量] from
(
select top 100 percent [ID]=2,[尺码]=left(name,2)
from syscolumns
where id=object_id('A') and
name like '[0-9]%'
order by [尺码]
)A
left join
(select [IDa]=2,[货号]
from A group by [货号]
)t on 1>0
left join
(
select [IDb]=1,[货号],[尺码]='34',[数量]=[34码] from A
union
select 2,[货号],'35',[35码] from A
union
select 2,[货号],'36',[36码] from A
union
select 2,[货号],'37',[37码] from A
union
select 2,[货号],'38',[38码] from A
union
select 2,[货号],'39',[39码] from A
union
select 2,[货号],'40',[40码] from A
)B on A.[尺码]=B.[尺码] and B.[货号]=t.[货号]
union
select 1,[货号],[尺码]='总数',[数量]=sum([总数])
from A group by [货号]
)tb
order by [货号],ID
--删除测试环境
drop table A
--结果
/*
货号 尺码 数量
---- ---- -----------
A 总数 88
A 34 10
A 35 20
A 36 0
A 37 40
A 38 5
A 39 6
A 40 7
B 总数 36
B 34 1
B 35 5
B 36 6
B 37 0
B 38 8
B 39 10
B 40 6
(所影响的行数为 16 行)
*/Top
6 楼opqhjb(又回来做程序员了!苦呀!)回复于 2005-08-04 17:24:08 得分 0
关注!!Top




