How to add XML data type in a GROUP BY clause?(如何在 GROUP BY 子句中添加 XML 数据类型?)
问题描述
我正在创建一个论坛,所以我创建了一个包含帖子的表格.其中一个字段是 Body
,类型为 XML
.现在我想创建一个查询,返回所有帖子和每个帖子的子项数量.我正在使用聚合函数执行此操作.当我使用聚合函数时,我需要使用一个组.当我使用 group by
中的字段时,会出现以下异常:
I'm creating a forum, so I have created a table with posts. One of the fields is a Body
with of the type XML
. Now I would like to create a query that returns all the posts and the number of children of every post. I'm doing this with an aggregate function. I need to use a group by when I'm using aggregate function. When I use the field in the group by
, I'll get the following exception:
XML 数据类型无法比较或排序,除非使用IS NULL 运算符.
The XML data type cannot be compared or sorted, except when using the IS NULL operator.
我该如何解决这个问题?
How can I solve this?
我的查询是:
SELECT
Post.PostId, Post.[Body], Count(Children.PostId)
FROM
dbo.Post Post,
dbo.Post Children
WHERE
Children.ParentId = Post.PostId
GROUP BY
Post.PostId,
Post.[Body]
推荐答案
您可以在 CTE 中进行聚合,然后加入该聚合
You can do the aggregation in a CTE then join onto that
WITH Children(Cnt, ParentId)
AS (SELECT COUNT(*),
ParentId
FROM dbo.Post
GROUP BY ParentId)
SELECT P.PostId,
P.[Body],
ISNULL(Cnt, 0) AS Cnt
FROM dbo.Post P
LEFT JOIN Children /*To include childless posts*/
ON Children.ParentId = P.PostId
ORDER BY P.PostId
这篇关于如何在 GROUP BY 子句中添加 XML 数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 GROUP BY 子句中添加 XML 数据类型?


- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- SQL 临时表问题 2022-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 更改自动增量起始编号? 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01