带有Group BY的XML路径子查询导致聚合错误

时间:2018-06-30 07:06:58

标签: sql-server tsql

我有以下查询,但我真的对如何获得返回结果并避免出现以下错误深感困惑。

信息144,第15层,状态1,第40行 不能在用于GROUP BY子句的group by列表的表达式中使用聚合或子查询。

SELECT Stuff((SELECT ', ' + typename 
              FROM   visittype VD 
                     LEFT JOIN lookup.type D 
                            ON VD.typeid = D.typeid 
              WHERE  visitid = V.visitid 
              ORDER  BY D.typename 
              FOR xml path(''), type).value('text()[1]', 'NVARCHAR(MAX)'), 1, 1, 
       N'') 
                AS Value1, 
       Count(*) AS Value2 
FROM   visit V 
WHERE  V.startdate >= '2018-03-31 14:00:00.0000000 +00:00' 
       AND V.enddate <= '2018-06-30 13:59:59.9990000 +00:00' 
GROUP  BY Stuff((SELECT ', ' + typename 
                 FROM   visittype VD 
                        LEFT JOIN lookup.type D 
                               ON VD.typeid = D.typeid 
                 WHERE  visitid = V.visitid 
                 ORDER  BY D.typename 
                 FOR xml path(''), type).value('text()[1]', 'NVARCHAR(MAX)'), 1, 
          1, N'') 

1 个答案:

答案 0 :(得分:1)

您可以使用subquery / cte:

WITH cte AS (
     SELECT Stuff((SELECT ', ' + typename 
              FROM   visittype VD 
              LEFT JOIN lookup.type D 
                ON VD.typeid = D.typeid 
              WHERE  visitid = V.visitid 
              ORDER  BY D.typename 
              FOR xml path(''), type).value('text()[1]', 'NVARCHAR(MAX)'), 1, 1, 
       N'') AS Value1
    FROM   visit V 
    WHERE V.startdate >= '2018-03-31 14:00:00.0000000 +00:00' 
      AND V.enddate <= '2018-06-30 13:59:59.9990000 +00:00' 
)
SELECT  Value1, COUNT(*) AS Value2
FROM cte
GROUP BY Value1;