下面的查询产生这两行(lastinspectionid,pastduereccount):
F5EF6588-4128-47D8-B185-002E9889D87A, htmlfromqueryrow1
F5EF6588-4128-47D8-B185-002E9889D87A, htmlfromqueryrow2
我想将这些列连接到pastduereccount列的单行中。
似乎无法获取xml的内容以使用下面的子查询。
select lastinspectionid, PastDueRecCount2 = stuff((select ' ' + PastDueRecCount for xml path('')),1,1,'')
from
(
select lastinspectionid, '<span style=''padding:3px;background-color:' + rowcolor + '''>' + convert(nvarchar(10),count(lastinspectionid)) + '</span>' as PastDueRecCount
from
(
select [LastInspectionID], rowcolor = case when DATEDIFF(day,[DueDate],getdate()) < 0 then '#FFCE8A' when DATEDIFF(day,[DueDate],getdate()) > 0 then '#FFA6A6' end
FROM
[dbo].[ReferenceRecommendations]
group by [LastInspectionID],[DueDate] HAVING Count(DATEDIFF(day,[DueDate],getdate())) > -7
) a
where rowcolor is not null
group by lastinspectionid, rowcolor
) as b group by lastInspectionID
答案 0 :(得分:0)
cte可以在子查询中使用cte:
with cte1 as
(
select lastinspectionid, '<span style=''padding:3px;background-color:' + rowcolor + '''>' + convert(nvarchar(10),count(lastinspectionid)) + '</span>' as PastDueRecCount
from
(
select [LastInspectionID], rowcolor = case when DATEDIFF(day,[DueDate],getdate()) < 0 then '#FFCE8A' when DATEDIFF(day,[DueDate],getdate()) > 0 then '#FFA6A6' end
FROM
[dbo].[ReferenceRecommendations]
group by [LastInspectionID],[DueDate] HAVING Count(DATEDIFF(day,[DueDate],getdate())) > -7
) as a
where rowcolor is not null
group by lastinspectionid, rowcolor
)
select
lastinspectionid,stuff((select' ' + PastDueRecCount from cte1 b where cte1.LastInspectionID = b.LastInspectionID for xml path('')),1,1,'')
from
cte1 group by LastInspectionID