sql - 合并sql中的列
问题描述
我正在使用 SQL Server 2017 有一个存储过程,其中我有一个简单的选择,其中包含如下连接:
SELECT
[p].[legacyKey] AS JobNumber
, [p].[Name] AS JobName
, [G].[Label] AS DesignStatus
, [GS].[Description] AS ShopStatus
, [JN].Title
, [JN].Note
, 'Remove' AS [Remove]
FROM [Project] AS [P]
INNER JOIN [Customer] AS [c] ON [P].[CustomerSoldById] = [C].[CustomerKey]
INNER JOIN [General] AS [G] ON [P].[StatusKey] = [G].[GeneralKey]
INNER JOIN [General] AS [GS] ON [P].[ShopsStatus] = [GS].[GeneralKey]
INNER JOIN ProjectDesign AS PD ON P.ProjectKey = PD.ProjectKey
INNER JOIN DESIGN AS D ON PD.DesignKey = D.DesignKey
INNER JOIN JobNotes AS JN ON PD.DesignKey = JN.DesignKey
WHERE [G].[Extended] = 'Project Status'
and p.LegacyKey = 18213
此查询的结果是:
+-----------+----------+--------------+------------+--------+-------------------+--------+
| JobNumber | JobNAme | DesignStatus | ShopStatus | Title | Note | Remove |
+-----------+----------+--------------+------------+--------+-------------------+--------+
| 1234 | TestName | Correct | Inc | Title1 | Note test design | Remove |
| 1234 | TestName | Correct | Inc | Title2 | note test proyect | Remove |
+-----------+----------+--------------+------------+--------+-------------------+--------+
Title
如您所见,除了和列之外,所有列都完全相同Note
,是否可以合并 Title 和 Note 以获得一列而不是两列?,示例:
+-----------+----------+--------------+------------+--------------------------------------------------------------+--------+--+
| JobNumber | JobNAme | DesignStatus | ShopStatus | Note | Remove | |
+-----------+----------+--------------+------------+--------------------------------------------------------------+--------+--+
| 1234 | TestName | Correct | Inc | Title1 : Note test design \n , Title2 : note test proyect \n | Remove | |
+-----------+----------+--------------+------------+--------------------------------------------------------------+--------+--+
我试试
CONCAT([JN].[Title], ': ', STRING_AGG([JN].[Note], '\N'))
但它只是将title
列与note
列连接,但没有将第 1 行与第 2 行合并,我做错了什么?问候
解决方案
concat()
然后使用string agg()
:
https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=69806c24356e5ef86fd0bfa7a239c82b
编辑1:如果您不想要/n
字符串中的最后一个值,您可以执行以下操作:
select left(string,len(string)-3)
from (
SELECT STRING_AGG(CONCAT(Title, ': ', Note, ' \n'),', ') as string
from test
) t
编辑 2:如果您有多个工作编号并且不希望所有值汇总到一行,您可以执行以下操作:
select left(string,len(string)-3)
from (
SELECT STRING_AGG(CONCAT(Title, ': ', Note, ' \n'),', ')
WITHIN GROUP (ORDER BY JobNumber) as string
from test
group by JobNumber
) t
推荐阅读
- reactjs - TextInput onChangeText 设置 useState 值在 React Native Testing with Enzyme 中不起作用
- java - 显示 3 个随机图像,在 Java 中没有双重显示?
- java - 从命令提示符运行 java 的问题
- java - 我可以使用 java 在 Instagram 关注者/关注窗口上进行向下滚动操作吗?
- ruby - 由于 NoMethod 错误和与我的 .gemspec 文件相关的问题,无法发布我的 Ruby gem
- javascript - 汉可以在单击按钮时增加setTimeout函数中的时间值吗?
- javascript - 无法使用 jquery 在输入字段中获取 Woocommerce 计费电话
- excel - 如果 table_2 任何地方包含来自 table_1 的 X、Y、Z 值,如何检查函数?
- amazon-web-services - Eureka Server 内存,更新阈值为 0,自我保存问题 - AWS
- python - 如何在 Python 中读取应用程序/八位字节流