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

求一条分组的 SQL语句
有A表和B表
A表
id,name,mark,time
B表
id AID worktime

是这样的
是一个日志类的需求
每一条日志下可以添加明细 就是B表
明细有个输入项 工作时长 worktime

比如 12月1日 下面有3个明细子信息 工作时长分别为 4 2 2
  12月2日 下面有2个明细子信息 工作时长分别为 3 1
 工作时长是存在B表的
执行SQL语句有 希望得到这么一个结果
日期 工作时长
12月1日 8
12月2 4

------解决方案--------------------
SQL code

select a.*,sum(b.worktime) as worktime
from a join b on a.id = b.aid
group by a.id,a.name,a.mark,a.time

------解决方案--------------------
SQL code
select a.id,a.name,a.mark,a.time,sum(b.worktime)
from A inner join B on a.id=b.aid
group by a.id,a.name,a.mark,a.time

------解决方案--------------------
SQL code

if object_id('A','U') is not null
   drop table A
go
create table A
(
 id int,
 name varchar(10),
 mark varchar(10),
 time datetime
)
go
insert into A
select 1,'A1','','2010-12-1' union all
select 2,'A2','','2010-12-2'
go
if object_id('B','U') is not null
   drop table B
go
create table B
(
 id int,
 AID int,
 worktime int
)
go
insert into B
select 1,1,4 union all
select 2,1,2 union all
select 3,1,2 union all
select 4,2,2 union all
select 5,2,2
go
select time,工作时间长=sum(worktime) from A inner join B on a.id=B.AId group by time
go
/*
time                    工作时间长
----------------------- -----------
2010-12-01 00:00:00.000 8
2010-12-02 00:00:00.000 4

(2 行受影响)
*/