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

关于分组的有关问题

2012-03-05 
关于分组的问题现有表AidtypeDateTimeamount1a2007-7-122a2007-7-263a2007-7-354b2007-7-235b2007-7-34查

关于分组的问题
现有表A
id       type           DateTime             amount
1           a               2007-7-1             2
2           a               2007-7-2             6
3           a               2007-7-3             5
4           b               2007-7-2             3  
5           b               2007-7-3             4
查询结果:
id       type           MaxDateTime       amount           sumAmount    
3           a               2007-7-3             5                       13
5           b               2007-7-3             4                       7
求出总数和最大时间对应的行


[解决办法]

Select
A.*,
B.sumAmount
From
A
Inner Join
(Select type, Max([DateTime]) As MaxDateTime, SUM(amount) As sumAmount From A Group By type) B
On A.type = B.type And A.[DateTime] = B.MaxDateTime
[解决办法]
select id,a1.type,maxdatetime, a1.amount,sumAmount from A a1
inner join (select type,max([datetime]) as maxdatetime,sum(amount) as sumAmount from A
group by type)b
on a1.type=b.type and a1.datetime=b.maxdatetime

--结果:
id type maxdatetime amount sumAmount
----- ------ -------------------------- ------- -----------
3 a 2007-07-03 00:00:00.000 5 13
5 b 2007-07-03 00:00:00.000 4 7

[解决办法]
select a.id ,a.type,x.maxdatetime,a.amount,x.sumamount
from (select type ,max(datetime) maxdatetime,sum(amount) sumamount
from a
group by type ) x
join a
on a.type=x.type
where a.datetime=x.maxdatetime

热点排行