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

求SQL语句(在等待.....)

表结构及数据如下
名称         数据       单价       金额  
  a             b               c             d
a               c               d             f
小计         b+c     (c+d)/2         d+f
bc           d                   c           f
bc           c                   e           h
小计       d+c         (c+e)/2       f+h
总计       b+c+d+c                     d+f+f+h
请大家帮忙,
谢谢


------解决方案--------------------
select case [order] when 1 then 名称 when 2 then '小计 ' else '总计 'end,
数据,单价,金额
from
(
select *,1[order] from #
union all
select 名称,sum(数据),sum(单价),sum(金额),2 from # group by 名称
union all
select max(名称),sum(数据),sum(单价),sum(金额),3 from #
)a
order by 名称,[order]
------解决方案--------------------
create table tb (名称 varchar(10),数据 int,单价 int,金额 int)
insert into tb values( 'a ',2,2,4)
insert into tb values( 'a ',2,4,8)
insert into tb values( 'b ',3,3,9)
insert into tb values( 'b ',5,5,25.00)

select * from tb
union all
select 名称 = case when 名称 is null then '合计 ' else 名称 + '小计 ' end,sum(数据) 数据,avg(单价) 单价,sum(金额) 金额
from tb
group by 名称
with rollup
order by 名称
drop table tb

/*
名称 数据 单价 金额
-------------- ----------- ----------- -----------
a 2 2 4
a 2 4 8
a小计 4 3 12
b 3 3 9
b 5 5 25
b小计 8 4 34
合计 12 3 46

(所影响的行数为 7 行)
*/
------解决方案--------------------
create table #table(名称 varchar(10), 数据 int,单价 int,金额 int)
insert into #table select 'a ',1,2,4
insert into #table select 'b ',3,1,6
insert into #table select 'b ',11,1,7
insert into #table select 'a ',2,13,5

select case [order] when 1 then 名称 when 2 then '小计 ' else '总计 'end,
数据,单价,金额
from
(
select *,1[order] from #
union all
select 名称,sum(数据),sum(单价)/count(1),sum(金额),2 from # group by 名称
union all
select max(名称),sum(数据),sum(单价)/count(1),sum(金额),3 from #
)a
order by 名称,[order]

------解决方案--------------------
借數據一用

create table tb (名稱 varchar(10),數據 int,單價 int,金額 int)
insert into tb values( 'a ',2,2,4)
insert into tb values( 'a ',2,4,8)
insert into tb values( 'b ',3,3,9)
insert into tb values( 'b ',5,5,25.00)

select * from tb
order by 名稱
compute sum(數據),avg(單價),sum(金額) by 名稱
compute sum(數據),sum(金額)


名稱 數據 單價 金額