T-SQL - 如何在xml对象上使用group by

时间:2016-09-07 15:07:59

标签: tsql sql-server-2012

我编写了以下查询,我希望返回查询

中概述的数据集

查询

SELECT 
RelatedRecordID AS [OrganisationID], 
Data.value('(//OpportunityViewEvent/Title)[1]','nvarchar(255)') AS OpportunityTitle,
Data.value('(//OpportunityViewEvent/ID)[1]','int') AS OpportunityID,
Count(Data.value('(//OpportunityViewEvent/ID)[1]','int')) AS Visits
FROM [Audit].[EventData]
LEFT OUTER JOIN Employed.Organisation AS ORG ON [EventData].RelatedRecordID = ORG.ID
Where EventTypeID = 4
Group BY RelatedRecordID
Order By Visits Desc

预期结果

+-----------------+-----------------+---------------+--------+
| OrganisationID  | OpportunityTitle | OpportunityID | Visits |  
+-----------------+------------------+---------------+--------+
|              23 | Plumber          |           122 |    567 |  
|              65 | Accountant       |            34 |    288 | 
|              12 | Developer        |            81 |    100 | 
|              45 | Driver           |            22 |     96 | 
+-----------------+------------------+---------------+--------+

我收到错误说

  

列'Audit.EventData.Data'在选择列表中无效,因为它   不包含在聚合函数或GROUP BY中   子句。

如果我然后尝试对xml数据进行分组,我会得到一个不同的错误

  

GROUP BY子句中不允许使用XML方法。

有办法解决这个问题吗?

由于

1 个答案:

答案 0 :(得分:1)

您可以将其添加到CTE中

;with cte as (
SELECT 
 RelatedRecordID AS [OrganisationID], 
 Data.value('(//OpportunityViewEvent/Title)[1]','nvarchar(255)') AS   OpportunityTitle,
 Data.value('(//OpportunityViewEvent/ID)[1]','int') AS OpportunityID,
 Data.value('(//OpportunityViewEvent/ID)[1]','int') as visit
FROM [Audit].[EventData]
LEFT OUTER JOIN Employed.Organisation AS ORG ON [EventData].RelatedRecordID = ORG.ID
Where EventTypeID = 4 )
select OrganisationID, opportunityTitle, opportunityId,  count(visit) as Visits from cte 
Group BY OrganisationID, opportunityTitle, opportunityId