首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

简单的groupby语句,挠头,该如何解决

2012-03-21 
简单的groupby语句,挠头假定已有数据库a,含表如话费统计.xls中的工作表2006年12月份A列是电话号码,B列是日

简单的groupby语句,挠头
假定已有数据库a,含表如   话费统计.xls中的工作表   2006年12月份

A列是电话号码,   B列是日期,   C列是金额
  2341                       20061212                     0.2
2341                         20061212                     0.2
2222                         20061212                     0.3
567720061220                     0.5
....


要求得到这个表中话费最多的6个电话号码,满足下面条件
1。以当天相同的电话号码,统计当天同一号码的总和
2。总和按从大到小排列,取前6位。

如何写sql语句呢?

谢谢


[解决办法]
1。以当天相同的电话号码,统计当天同一号码的总和
select aa.a,sum(aa.C) d from table aa inner join table bb on aa.a=bb.a and aa.b=bb.b group by aa.a order by d
2。总和按从大到小排列,取前6位。
select top 6 e.* from
(select aa.a,sum(aa.C) d from table aa inner join table bb on aa.a=bb.a and aa.b=bb.b group by aa.a order by d
) e
[解决办法]
A列是电话号码, B列是日期, C列是金额
2341 20061212 0.2
2341 20061212 0.2
2222 20061212 0.3
567720061220 0.5

select top 6 a from tab where b= '20061212 ' group by a order by sum(c)
[解决办法]
A列是电话号码, B列是日期, C列是金额
2341 20061212 0.2
2341 20061212 0.2
2222 20061212 0.3
567720061220 0.5
要求得到这个表中话费最多的6个电话号码,满足下面条件
1。以当天相同的电话号码,统计当天同一号码的总和
2。总和按从大到小排列,取前6位。


if object_id( 't ') is not null
drop table t
go
create table t(A varchar(20),B datetime,C float)
insert t select '2341 ', '2007-2-5 ',0.2
union all select '2345 ', '2006-12-12 ',0.2
union all select '2341 ', '2006-2-5 ',0.3
union all select '5767 ', '2006-12-20 ',0.5
union all select '2351 ', '2007-2-5 ',0.3
union all select '2352 ', '2007-2-5 ',0.3
union all select '2351 ', '2007-2-5 ',0.8
union all select '2352 ', '2007-2-5 ',0.3

go
select A,sum(C) from t where convert(varchar,B,110) = convert(varchar,getdate(),110) group by A

select top 6 A,sum(C) from t where
convert(varchar,B,110) = convert(varchar,getdate(),110) group by A order by sum(C) DESC

[解决办法]
select top 6 a,b,sum(c) as c from biao group by a,b order by c desc

热点排行