日期:2014-05-18  浏览次数:20455 次

请教如何进行表连接进行动态汇总统计
现有两个表
表1,各年度采购情况
含以下字段:部门名称,物品名称,数量,年度
A PC 5 2006
A Printer 1 2006
A Scanner 2 2006
B PC 8 2006
B Printer 2 2006
C DC 1 2006
C PC 2 2006
... ... ... ...

表2,物品名称,单价,年度
从表1提取物品名称、年度字段,填充本表
Insert into 表2 (名称,年度) Select Distinct 物品名称,年度 From 表1

问题:如何动态提取表1物品名称和年度填充表2,提供用户单价维护界面,将各年度各物品单价存储在表2,再对各部门各年

度采购金额进行汇总。结果表如下:
部门名称 物品名称 总额 年度
  合计 合计 200000 2006
  A 合计 40000 2006
  A PC 30000 2006
  A Printer 5000 2006
  A Scanner 5000 2006
  B 合计 53000 2006
  B PC 48000 2006
  B Printer 5000 2006
  C 合计 15000 2006
  C DC 3000 2006
  C PC 12000 2006
谢谢指导帮忙!


------解决方案--------------------
create table #table
(
 部门名称 varchar(50),
物品名称 varchar(50),
总额 varchar(50),
年度 varchar(50)
)
insert #table
select a.部门名称,a.物品名称,sum(a.数量×b.单价) as 总额,a.年度
from 表1 a inner join 表2 b on a.物品名称=b.物品名称
group by a.部门名称,a.物品名称,a.年度

insert #table
select a.部门名称,'合计',sum(a.数量×b.单价) as 总额,a.年度
from 表1 a inner join 表2 b on a.物品名称=b.物品名称
group by a.部门名称,a.年度

select * from #table
order by 部门名称,年度,总额 desc
------解决方案--------------------
SQL code
select * from
(
  select 部门名称,物品名称,sum(数量) 总额,年度=@年度 from tb where 年度=@年度 group by 部门名称,物品名称
  union all
  select 部门名称,物品名称='合计',sum(数量) 总额,年度=@年度 from tb where 年度=@年度 group by 部门名称
  union all
  select 部门名称='合计',物品名称='合计',sum(数量) 总额,年度=@年度 from tb where 年度=@年度
) t
order by case 部门名称 when '合计' then 1 else 2 end , case 物品名称 when '合计' then 1 else 2 end