【发布时间】:2016-06-30 07:05:57
【问题描述】:
有了这张桌子:
declare @table table
(
ID int not null IDENTITY(1,1),
day date,
hour int,
val int
)
insert into @table
values
('2016-06-15', 8, 1),
('2016-06-15', 9, 1),
('2016-06-15', 10, 7),
('2016-06-16', 8, 3),
('2016-06-15', 9, 3),
('2016-06-15', 10, 5)
这是某些查询的结果,该查询列出了每天和每小时的值。我正在使用我在某处找到的以下代码(我使用它,但我不太了解它)从@table 生成 html 表。
SELECT CAST((select 2 [@cellpadding]
,2 [@cellspacing]
,1 [@border]
, 'background-color: rgb(226, 140, 5)' [@style]
,(select th
from (select 'Day' th union all
select 'Hour' th
union all
select 'Val'
) d
for xml path(''),type) tr
,(select (select 'width:260px;vertical-align:top;background-color: white;' [@style], [Day] for xml path('td'),type),
(select 'width:260px;vertical-align:top;background-color: white;' [@style], [Hour] for xml path('td'),type),
(select 'width:260px;vertical-align:top;background-color: white;' [@style], val for xml path('td'),type)
from (
select t.day
, t.Hour
, t.val
FROM @table t
) data
for xml path ('tr'),type)
for xml path('table'), type) AS nvarchar(MAX))
这给了我一个像这样的 html 表格:
Day Hour Val
2016-06-15 8 1
2016-06-15 9 1
2016-06-15 10 7
2016-06-16 8 3
2016-06-16 9 3
2016-06-16 10 5
我想要的是这样的表格:
Day Hour Val
2016-06-15 8 1
9 1
10 7
2016-06-16 8 3
9 3
10 5
即不要重复相同的天数,仅在新的一天显示天数。
【问题讨论】:
-
我已经发布了答案,请查看
标签: sql sql-server sql-server-2012 for-xml-path for-xml