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

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

A列是电话号码,   B列是日期,   C列是金额
  2341                       20061212                     0.2
2341                         20061212                     0.2
2222                         20061212                     0.3
5677 20061220                     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
5677 20061220 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
5677 20061220 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