Sql server存储过程有助于执行以下查询

时间:2012-10-05 07:19:13

标签: sql-server stored-procedures

create table testjob  
(  
jobid int,  
jobname varchar(100),  
time float,  
name varchar(50),  
Date varchar(100),  
comments varchar(500)  
)

insert into testjob values ( 1001,'java work',4.5,'arjun','9/26/2012  12:00:00 AM','Sample test comments 1')
insert into testjob values ( 1005,'sql work',10,'arjun','9/28/2012  12:00:00 AM','Sample test comments 2')
insert into testjob values ( 1010,'.net work',7.5,'arjun','8/13/2012  12:00:00 AM','Sample test comments 3')
insert into testjob values ( 1040,'java work',5.5,'ravi','9/14/2012  12:00:00 AM','Sample test comments 1')
insert into testjob values ( 1023,'php work',2.5,'arjun','9/5/2012  12:00:00 AM','Sample test comments 4')
insert into testjob values ( 1027,'.net work',3.5,'ravi','8/24/2012  12:00:00 AM','Sample test comments 2')

我想要一个不使用游标的程序,以便我的输出如下:(如果可能的话,我希望使用带运算符的查询)

Name:Arjun(24.5 Hrs spent)

jobname          Time            Date                Comments  
java work     4.5     9/26/2012  12:00:00 AM   Sample test comments 1   
sql work      10      9/28/2012  12:00:00 AM   Sample test comments 2  
.net work     7.5     8/13/2012  12:00:00 AM   Sample test comments 3  
php  work     2.5     9/5/2012  12:00:00 AM    Sample test comments 4

Name:Ravi(9 Hrs spent)

jobname       time           Date             Comments  
java work     5.5     9/14/2012  12:00:00 AM   Sample test comments 1  
.net work     3.5     8/24/2012  12:00:00 AM   Sample test comments 2  

1 个答案:

答案 0 :(得分:3)

查看此SQL Fiddle

无需为您的查询使用WITH。

select name,case when jobname is null
                 then cast(sum(time) as varchar(12)) + ' hrs spent'
                 else jobname end jobname,time,date,comments
from testjob
group by grouping sets ((name),(name,jobname,time,date,comments))
order by name,comments

您不应该真正需要分组集,我只是将它包含在内,以向您展示如何使用查询工具中的汇总标头查看它。如果要将此数据传输到Visual Studio等前端工具,则应该在那里控制分组,并以简单的方式返回数据,例如

select name,jobname,time,date,comments
from testjob
order by name,comments
You keep a running total of time until the name changes.

仅供参考,你真的应该选择一个更好的排序顺序,例如'date'而不是'comments',但这是我发现的唯一一个给出你所展示的结果的顺序。