用于字符串连接的SUM和GROUP BY的类似物

时间:2013-05-31 11:06:07

标签: sql sql-server tsql

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

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 path。该解决方案的问题是大量的代码(我应该在STUFF子句中重写我的查询,生成非常长的查询)。 我有什么选择?

2 个答案:

答案 0 :(得分: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 with Demo

答案 1 :(得分:0)

您不必两次编写长代码。编写你真正很长的代码,获取你希望你的内部xml路径('')查询作为公共表表达式处理的结果集:

--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