读书人

求SQL语句(在等待.)解决方法

发布时间: 2012-01-19 00:22:28 作者: rapoo

求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(金)


名 金


---------- ----------- ----------- -----------
a 2 2 4
a 2 4 8

sum
===========
4

avg
===========
3

sum
===========
12


名 金
---------- ----------- ----------- -----------
b 3 3 9
b 5 5 25

sum
===========
8

avg
===========
4

sum
===========
34


sum
===========
12

sum
===========
46


(7 row(s) affected)



[解决办法]
create table #TableName(名称 varchar(20), 数据 float,单价 float,金额 float)
declare @name varchar(20)
declare @data int
declare @price ine
declare @moneys float

DECLARE Cur1 cursor for
SELECT 名 ,sum(),sum()/count(名),sum(金额)
FROM TableName
Group by 名

OPEN Cur1
FETCH next from Cur1 INTO @name, @data , @price, @moneys

WHILE @@fetch_status <> -1
BEGIN
Insert Into #TableName
Select * From TableName Where 名=@name
Insert Into #TableName
select @name as @name+ '小 ', @data , @price, @moneys )

FETCH next from Cur1 INTO @name, @data , @price, @moneys
END
CLOSE Cur1
DEALLOCATE Cur1
Insert Into #TableName
Select '合 ',sum(), ' ',sum(金额)
Select * from #TableName
Order by 名
Drop table #TableName

读书人网 >SQL Server

热点推荐