Tsql T-SQL-如何在xml对象上使用GROUPBY
我已经编写了以下查询,我希望返回一个数据集,如查询中所述 质疑 预期结果 我收到一个错误,说 列“Audit.EventData.Data”在选择列表中无效,因为它 未包含在聚合函数或GROUP BY中 条款 如果我尝试对xml数据进行分组,则会出现另一个错误,即 GROUPBY子句中不允许使用XML方法 有办法解决这个问题吗Tsql T-SQL-如何在xml对象上使用GROUPBY,tsql,sql-server-2012,Tsql,Sql Server 2012,我已经编写了以下查询,我希望返回一个数据集,如查询中所述 质疑 预期结果 我收到一个错误,说 列“Audit.EventData.Data”在选择列表中无效,因为它 未包含在聚合函数或GROUP BY中 条款 如果我尝试对xml数据进行分组,则会出现另一个错误,即 GROUPBY子句中不允许使用XML方法 有办法解决这个问题吗 谢谢您可以将其添加到CTE中 ;with cte as ( SELECT RelatedRecordID AS [OrganisationID], Data.va
谢谢您可以将其添加到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
“选择”在“分组依据”之后处理。如果你想对select的结果进行分组,你应该使用子查询,例如select。。。从选择。。。来自EventData x GROUP By…感谢您的建议,我也将尝试这种方式。
+-----------------+-----------------+---------------+--------+
| OrganisationID | OpportunityTitle | OpportunityID | Visits |
+-----------------+------------------+---------------+--------+
| 23 | Plumber | 122 | 567 |
| 65 | Accountant | 34 | 288 |
| 12 | Developer | 81 | 100 |
| 45 | Driver | 22 | 96 |
+-----------------+------------------+---------------+--------+
;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