SQL:连接与给定键匹配的所有字段?
假设我有一个像这样的 SQL 查询:
SELECT
tickets.TicketNumber, history.remarks
FROM
AT_DeviceReplacement_Tickets tickets
INNER JOIN
AT_DeviceReplacement_Tickets_History history
ON tickets.TicketNumber = history.TicketNumber;
我在回复中得到一个这样的表:
ticketNumber | remarks
-------------+------------
1 | "Hello, there is a problem."
1 | "Did you check the power cable?
1 | "We plugged it in and now it works. Thank you!"
2 | "Hello, this is a new ticket."
假设我想编写一个查询来连接每张票证的备注并返回这样的表:
ticketNumber | remarks
-------------+------------
1 | "Hello, there is a problem.Did you check the power cable?We plugged it in and now it works. Thank you!"
2 | "Hello, this is a new ticket."
是的,在真实的代码中,我'实际上,除其他外,我们已经按日期排序了这些内容,但为了讨论,我将如何编辑上面的查询以获得我描述的结果?
Suppose I have a SQL query like this:
SELECT
tickets.TicketNumber, history.remarks
FROM
AT_DeviceReplacement_Tickets tickets
INNER JOIN
AT_DeviceReplacement_Tickets_History history
ON tickets.TicketNumber = history.TicketNumber;
I get a table like this in repsonse:
ticketNumber | remarks
-------------+------------
1 | "Hello, there is a problem."
1 | "Did you check the power cable?
1 | "We plugged it in and now it works. Thank you!"
2 | "Hello, this is a new ticket."
Suppose that I want to write a query that will concatenate the remarks for each ticket and return a table like this:
ticketNumber | remarks
-------------+------------
1 | "Hello, there is a problem.Did you check the power cable?We plugged it in and now it works. Thank you!"
2 | "Hello, this is a new ticket."
Yes, in the real code, I've actually got these sorted by date, among other things, but just for the sake of discussion, how would I edit the above query to get the result I described?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查看以下问题:
我可以吗逗号将多行分隔成一列?
是否可以使用 CTE 将列值连接成字符串?
Have a look at the following questions:
Can I Comma Delimit Multiple Rows Into One Column?
Is it possible to concatenate column values into a string using CTE?
此问题最干净的解决方案是依赖于数据库的。 Lentine 的链接显示了 Oracle 和 SQL Server 的非常丑陋的解决方案以及 MySQL 的干净解决方案。 PostgreSQL 中的答案也非常简短和简单。
(请注意,示例代码中同时包含 Ticket_number 和 TicketNumber。)
我的猜测是,Oracle 和 SQL Server 要么 (1) 具有类似的聚合函数,要么 (2) 具有定义您自己的聚合函数的能力。 [对于 MySQL,等效的聚合称为 GROUP_CONCAT。] 您使用什么数据库?
The cleanest solution to this problem is DB dependent. Lentine's links show very ugly solutions for Oracle and SQL Server and a clean one for MySQL. The answer in PostgreSQL is also very short and easy.
(Note you have both ticket_number and TicketNumber in your sample code.)
My guess is that Oracle and SQL Server either (1) have a similar aggregate function or (2) have the capability of defining your own aggregate functions. [For MySQL the equivalent aggregate is called GROUP_CONCAT.] What DB are you using?