首页 > 解决方案 > Move an object up and separate based on item

问题描述

I have the following problem:

Apple  | Document 1 | 5
Orange | Document 2 | 4
Apple  | Document 3 | 7

What I would like to happen with a query is the following:

Apple  | Document 1 | Document 3 | 12
Orange | Document 2              | 7

Is there a function that does this for you?

标签: sql-servertsqlaggregate-functions

解决方案


在 SQL Server 2017 中,您可以使用以下STRING_AGG功能GROUP BY

SELECT fruit, STRING_AGG(document, '|') AS documents, SUM(value) AS total
FROM t
GROUP BY fruit

推荐阅读