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

求各位前辈一个问题,关于汇总的问题

有一个类似这样的表格,

a     10000  
b     1000
a     2000
b     300
c     40000
c     400

想得到的查询结果:
实现这样的目的:
ID     SALEAMT   标识
a     10000     0
a     2000       0
a     12000     1
b     1000       0
b     300         0
b     1300       1
c     40000     0
c     400         0
c     40400     1

以惟一列ID为准,在每一个项目中,加一个汇总。其中的标识是为了排序用。

------解决方案--------------------
select * from
(select ID,SALEAMT,0 as 标识 from YourTable
union all select id,sum(SALEAMT) as SALEAMT,1 as 标识 from YourTable group by id
) a
order by id,标识

------解决方案--------------------
Create Table TEST
(ID Varchar(10),
SALEAMT Int)
Insert TEST Select 'a ', 10000
Union All Select 'b ', 1000
Union All Select 'a ', 2000
Union All Select 'b ', 300
Union All Select 'c ', 40000
Union All Select 'c ', 400
GO
--方法一
Select
ID,
SALEAMT,
0 As 标识
From
TEST
Union
Select
ID,
SUM(SALEAMT) As SALEAMT,
1 As 标识
From
TEST
Group By
ID
Order By
ID, 标识

--方法二
Select
ID,
SUM(SALEAMT) As SALEAMT
From
TEST
Group By
ID, SALEAMT
With Rollup
Having ID Is Not Null
GO
Drop Table TEST
--Result
/*
ID SALEAMT 标识
a 2000 0
a 10000 0
a 12000 1
b 300 0
b 1000 0
b 1300 1
c 400 0
c 40000 0
c 40400 1

ID SALEAMT
a 2000
a 10000
a 12000
b 300
b 1000
b 1300
c 400
c 40000
c 40400
*/