0

假设我有一个很长的查询:

select T.TipoVers As TypeVers,
       sum(T.ImpTot) As N, 
       C.DataCalendario As Date, 
from ( SELECT ... )
group by C.DataCalendario, T.TipoVers 

这会产生如下输出:

 TypeVers     N      Date
================================
   Type1      1    2012-09-10
   Type2      47   2012-09-10 
   Type3      5    2012-09-11

我几乎完成了,但最后一点是:date需要连接相同的行(对于字符串值)并求和(对于数值 - 现在这是唯一有效的部分),即:

   TypeVers       N       Date
====================================
  Type1,Type2     48    2012-09-10
     Type3        5     2012-09-11

我在这里阅读了有关XML 路径的信息。该解决方案的问题是代码量很大(我应该在 STUFF 子句中重写我的查询,生成非常长的查询)。我有什么选择?

4

2 回答 2

2

如果您不想再次编写查询,那么我建议您使用 CTE,以便您可以在STUFF/FOR XML PATH查询中自行引用它:

;with cte as
(
  select typeVers, n, date  -- your current query will go here
  from yd 
) 
select STUFF((SELECT DISTINCT ', ' + TypeVers 
              FROM cte t
              WHERE c.Date = t.Date
              FOR XML PATH('')), 1, 1, '') TypeVers,
  sum(n) n,
  date
from cte c
group by date;

请参阅带有演示的 SQL Fiddle

于 2013-05-31T11:20:32.777 回答
0

您不必编写两次长代码。编写非常长的代码,以获取您希望内部 for xml path('') 查询作为公共表表达式工作的结果集:

--Creates a common table expression that we can reference more than once in the select.
WITH myLongQueryCTE AS
(
SELECT
ROW_NUMBER() over (order by something) AS SOME_UNIQUE_COLUMN --Put you unique column here or create a new one with row_number
,TipoVers 
,ImpTot
,DataCalendario 
...
GROUP BY DataCalendario
)

SELECT
STUFF((SELECT ', ' + TipoVers FROM myLongQueryCTE AS a WHERE a.SOME_UNIQUE_COLUMN = b.SOME_UNIQUE_COLUMN FOR XML PATH('')),1,1,'') as TypeVers
,SUM(ImpTot) AS N
,DataCalendario AS Date
FROM myLongQueryCTE AS b
于 2013-05-31T11:28:05.477 回答