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

分组获取最小时间行另外一列的和

2013-01-01 
求助:分组获取最小时间行另外一列的和如下面脚本,根据a分组,获取最小的时间列,然后求B列的和create table

求助:分组获取最小时间行另外一列的和
如下面脚本,根据a分组,获取最小的时间列,然后求B列的和



create table #tb(a ID,dt datetime,b int,c int)

insert into #tb
select 1,N'2012-12-12', 1,2 union all
select 2,N'2012-12-12', 4,0 union all
select 3,N'2012-12-12', 8,3 union all
select 2,N'2012-12-12', 5,5 union all
select 1,N'2012-12-13', 14,13 union all
select 5,N'2012-12-13', 14,18 union all
select 3,N'2012-12-13', 21,33 union all
select 4,N'2012-12-13', 11,53 union all
select 5,N'2012-12-13', 11,25 union all
select 6,N'2012-12-13', 22,33 union all
select 3,N'2012-12-14', 27,33 union all
select 4,N'2012-12-14', 25,13 union all
select 8,N'2012-12-14', 32,53 union all
select 3,N'2012-12-14', 35,93  



[解决办法]


create table #tb(a int,dt datetime,b int,c int)

insert into #tb
select 1,N'2012-12-12', 1,2 union all
select 2,N'2012-12-12', 4,0 union all
select 3,N'2012-12-12', 8,3 union all
select 2,N'2012-12-12', 5,5 union all
select 1,N'2012-12-13', 14,13 union all
select 5,N'2012-12-13', 14,18 union all
select 3,N'2012-12-13', 21,33 union all
select 4,N'2012-12-13', 11,53 union all
select 5,N'2012-12-13', 11,25 union all
select 6,N'2012-12-13', 22,33 union all
select 3,N'2012-12-14', 27,33 union all
select 4,N'2012-12-14', 25,13 union all
select 8,N'2012-12-14', 32,53 union all
select 3,N'2012-12-14', 35,93  

select
a,
dt,
sum(b) as b
from
#tb a
where
a.dt=(select min(dt) from #tb where a.a=a)
group by
a,dt
/*
adtb
12012-12-12 00:00:00.0001
22012-12-12 00:00:00.0009
32012-12-12 00:00:00.0008
42012-12-13 00:00:00.00011
52012-12-13 00:00:00.00025
62012-12-13 00:00:00.00022
82012-12-14 00:00:00.00032
*/

热点排行
Bad Request.