我不确定您使用的是什么数据库引擎,但下面的示例使用 Microsoft SQL Server。我相信它可以很容易地适应其他引擎。
首先,我使用以下查询创建了一些设置数据:
create table tasks(
[id] int not null identity(1,1),
[DATE] smalldatetime not null,
project_id int not null,
spent_time int not null,
primary key ([id])
)
go
insert into tasks([date],project_id,spent_time)
select '2012-04-02',1,10
union all select '2012-04-02',1,5
union all select '2012-04-02',2,5
union all select '2012-04-03',1,8
union all select '2012-04-03',2,1
go
正如上面评论中提到的,您需要动态生成 SQL 语句。我在变量@sql 中执行此操作,然后在最后执行它。这是我的解决方案:
declare @sql nvarchar(4000), @project_id nvarchar(10)
select @sql = 'select [date]'
declare c cursor for select distinct convert(nvarchar(10),project_id) as project_id from tasks order by project_id
open c
fetch c into @project_id
while @@FETCH_STATUS = 0
begin
select @sql = @sql + ', sum(case when project_id = ' + @project_id + ' then spent_time else 0 end) as project_' + @project_id
fetch c into @project_id
end
close c
deallocate c
select @sql = @sql + ', sum(spent_time) as sum_of_projects from tasks group by [date] order by [date]'
exec (@sql)
正如我的测试数据所预期的那样,它会生成输出:
date project_1 project_2
---- --------- ---------
2012-04-02 15 5
2012-04-03 8 1
希望这可以帮助!
更新
OP 已经表示希望避免使用游标,因此以下代码也可以在不使用游标的情况下工作(至少在 MS SQL Server 上)......
declare @sql nvarchar(4000), @project_id nvarchar(10)
select @sql = 'select [date]'
select @sql = @sql + ', sum(case when project_id = ' + project_id + ' then spent_time else 0 end) as project_' + project_id
from (select distinct CONVERT(nvarchar(10), project_id) as project_id from tasks) q
select @sql = @sql + ', sum(spent_time) as sum_of_projects from tasks group by [date] order by [date]'
exec (@sql)