有一张表,我想变成下表的样子

84175971 2005-10-04 10:23:07
表1
日期 产品1 产品2 年月
零售价 5 2 200508
01 5 6 200508
02 6 8 200508
03 4 9 200508
04 3 2 200508
零售价 4.5 2.5 200511
01 3 5 200511
02 2 6 200511
03 1 1 200511
04 4 1 200511

经过sql语言后变成下表2
汇总 年月 产品1 产品2
销售数量 200508 18 25
销售金额 200508 90 50
销售数量 200511 10 13
销售金额 200511 45 32.5

这样的表该如何做呢
...全文
141 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
84175971 2005-10-08
  • 打赏
  • 举报
回复
精彩,精彩,太精彩了
zxbyhcsdn 2005-10-07
  • 打赏
  • 举报
回复
这个表设计得也太¥!%……#¥%!!·

汗!!!!!
$扫地僧$ 2005-10-06
  • 打赏
  • 举报
回复
create table 表1 (日期 varchar(10),产品1 float,产品2 float,年月 varchar(10))
insert 表1 select '零售价',5,2,'200508'
insert 表1 select '01',5,6,'200508'
insert 表1 select '02',6,8,'200508'
insert 表1 select '03',4,9,'200508'
insert 表1 select '04',3,2,'200508'
insert 表1 select '零售价',4.5,2.5,'200511'
insert 表1 select '01',3,5,'200511'
insert 表1 select '02',2,6,'200511'
insert 表1 select '03',1,1,'200511'
insert 表1 select '04',4,1,'200511'


select T_table.* from (select '销售数量' as 汇总 ,年月,sum(产品1)as 产品1,Sum(产品2) as 产品2 from 表1 where 日期<>'零售价' group by 年月
union
select '销售金额' as 汇总,表1.年月,sum(表1.产品1*T.产品1)as 产品1,Sum(表1.产品2*T.产品2) as 产品2 from 表1,(select 年月,产品1,产品2 from 表1 where 日期='零售价') T
where 表1.日期<>'零售价'
and 表1.年月=T.年月
group by 表1.年月) T_table
order by 年月
84175971 2005-10-06
  • 打赏
  • 举报
回复
up
jxdjxd1111 2005-10-06
  • 打赏
  • 举报
回复
简单点的:
declare @a table(日期 char(20),产品1 real,产品2 real, 年月 char(20))
insert into @A SELECT '零售价', 5,2,'200508' union
select '01', 5, 6,'200508' UNION
SELECT '02', 6, 8,'200508' UNION
SELECT '03', 4, 9,'200508' UNION
SELECT '04', 3, 2,'200508' UNION
SELECT '零售价',4.5,2.5,'200511' UNION
SELECT '01', 3, 5 ,'200511' UNION
SELECT '02', 2, 6, '200511' UNION
SELECT '03', 1, 1,'200511' UNION
SELECT '04', 4, 1,'200511'


select '销售数量' as 汇总 ,年月,sum(产品1)as 产品1,Sum(产品2) as 产品2
from @a where 日期<>'零售价' group by 年月
union all
select '销售金额' as 汇总,a.年月,产品1=sum(产品1)*(select 产品1 from @a where 年月=a.年月 AND 日期='零售价'),
产品2 =Sum(产品2)*(select 产品2 from @a where 年月=a.年月 AND 日期='零售价')
from @a a where 日期<>'零售价' group by 年月
order by 年月,汇总 desc
--经过sql语言后变成下表2
-- 汇总 年月 产品1 产品2
销售数量 200508 18.0 25.0
销售金额 200508 90.0 50.0
销售数量 200511 10.0 13.0
销售金额 200511 45.0 32.5

27,582

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧