在 SQL Server 2016 中将 GROUP BY 与 FOR XML PATH 结合使用
Using GROUP BY with FOR XML PATH in SQL Server 2016
我正在尝试
- 按 ID 分组
- 将多个评论聚合成一行
现在,我可以做到不。单个 ID (ID = 1006
) 的 2 部分,但我想汇总所有 ID 的评论。我正在努力在我的查询中添加“group by”子句的位置和方式。
这里是查询:
create table Comments (ID int, Comment nvarchar(150), RegionCode int)
insert into Comments values (1006, 'I', 1)
, (1006, 'am', 1)
, (1006, 'good', 1)
, (1006, 'bad', 2)
, (2, 'You', 1)
, (2, 'are', 1)
, (2, 'awesome', 1)
SELECT
SUBSTRING((SELECT Comment
FROM Comments
WHERE ID = 1006 AND RegionCode != 2
FOR XML PATH('')), 1, 999999) AS Comment_Agg
我想要的结果是这样的:
仅供参考,我在这里使用 FOR XML PATH
将多个评论聚合到一行中,因为我的版本不支持 STRING_AGG
功能 - SQL Server 2016(v13.x).
请尝试以下解决方案。
SQL
-- DDL and sample data population, start
DECLARE @tbl TABLE (ID int, Comment nvarchar(150));
INSERT INTO @tbl VALUES
(1006, 'I'),
(1006, 'am'),
(1006, 'good'),
(2, 'You'),
(2, 'are'),
(2, 'awesome');
-- DDL and sample data population, end
DECLARE @separator CHAR(1) = SPACE(1);
SELECT p.ID
, STUFF((SELECT @separator + Comment
FROM @tbl AS c
WHERE c.ID = p.ID
FOR XML PATH('')), 1, LEN(@separator), '') AS Result
FROM @tbl AS p
GROUP BY p.ID
ORDER BY p.ID;
输出
+------+-----------------+
| ID | Result |
+------+-----------------+
| 2 | You are awesome |
| 1006 | I am good |
+------+-----------------+
我正在尝试
- 按 ID 分组
- 将多个评论聚合成一行
现在,我可以做到不。单个 ID (ID = 1006
) 的 2 部分,但我想汇总所有 ID 的评论。我正在努力在我的查询中添加“group by”子句的位置和方式。
这里是查询:
create table Comments (ID int, Comment nvarchar(150), RegionCode int)
insert into Comments values (1006, 'I', 1)
, (1006, 'am', 1)
, (1006, 'good', 1)
, (1006, 'bad', 2)
, (2, 'You', 1)
, (2, 'are', 1)
, (2, 'awesome', 1)
SELECT
SUBSTRING((SELECT Comment
FROM Comments
WHERE ID = 1006 AND RegionCode != 2
FOR XML PATH('')), 1, 999999) AS Comment_Agg
我想要的结果是这样的:
仅供参考,我在这里使用 FOR XML PATH
将多个评论聚合到一行中,因为我的版本不支持 STRING_AGG
功能 - SQL Server 2016(v13.x).
请尝试以下解决方案。
SQL
-- DDL and sample data population, start
DECLARE @tbl TABLE (ID int, Comment nvarchar(150));
INSERT INTO @tbl VALUES
(1006, 'I'),
(1006, 'am'),
(1006, 'good'),
(2, 'You'),
(2, 'are'),
(2, 'awesome');
-- DDL and sample data population, end
DECLARE @separator CHAR(1) = SPACE(1);
SELECT p.ID
, STUFF((SELECT @separator + Comment
FROM @tbl AS c
WHERE c.ID = p.ID
FOR XML PATH('')), 1, LEN(@separator), '') AS Result
FROM @tbl AS p
GROUP BY p.ID
ORDER BY p.ID;
输出
+------+-----------------+
| ID | Result |
+------+-----------------+
| 2 | You are awesome |
| 1006 | I am good |
+------+-----------------+