我有一张如下表:
create table testjob
(
jobid int,
jobname varchar(100),
time float,
name varchar(50)
)
insert into testjob values ( 1001,'java work',4.5,'arjun')
insert into testjob values ( 1005,'sql work',10,'arjun')
insert into testjob values ( 1010,'.net work',7.5,'arjun')
insert into testjob values ( 1040,'java work',5.5,'ravi')
insert into testjob values ( 1023,'php work',2.5,'arjun')
insert into testjob values ( 1027,'.net work',3.5,'ravi')
我想要一个程序,以便我的输出如下所示的html格式如下:
Name: Arjun (24.5 Hrs spent)
jobname Time
java work 4.5
sql work 10
.net work 7.5
php work 2.5
Name: Ravi(9 Hrs spent)
jobname time
java work 5.5
.net work 3.5
答案 0 :(得分:1)
--detail template
declare @strDTmp nvarchar(200) = '<td>[job]</td><td>[hrs]</td>'
--sum template
declare @strSTmp nvarchar(200) = 'Name: [name] ([hrs] Hrs spent)'
--Table head
declare @strThead nvarchar(200) = '<th>jobname</th><th>Time</th>'
select
replace(replace(@strSTmp,'[name]',name),'[hrs]',stime) h1
,(
select
tr
from
(
select
0 pos
,name
,@strThead tr
from
testjob
group by
name
union all
select
1 pos
,name
,replace(replace(@strDTmp,'[job]',jobname),'[hrs]',time) tr
from
testjob
) t
where
t.name = sumtable.name
order by
pos
FOR XML PATH(''), root('table'), type
)
from
(
select
name
,sum(time) stime
from
testjob sumtable
group by
name
) sumtable
FOR XML PATH ('')
结果:
<h1>Name: arjun (24.5 Hrs spent)</h1>
<table>
<tr><th>jobname</th><th>Time</th></tr>
<tr><td>java work</td><td>4.5</td></tr>
<tr><td>sql work</td><td>10</td></tr>
<tr><td>.net work</td><td>7.5</td></tr>
<tr><td>php work</td><td>2.5</td></tr>
</table>
<h1>Name: ravi (9 Hrs spent)</h1>
<table>
<tr><th>jobname</th><th>Time</th></tr>
<tr><td>java work</td><td>5.5</td></tr>
<tr><td>.net work</td><td>3.5</td></tr>
</table>