假设我有这样的SQL查询:
SELECT
tickets.TicketNumber, history.remarks
FROM
AT_DeviceReplacement_Tickets tickets
INNER JOIN
AT_DeviceReplacement_Tickets_History history
ON tickets.TicketNumber = history.TicketNumber;
我在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."
假设我想编写一个查询来连接每个故障单的备注并返回一个这样的表:
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."
是的,在真实的代码中,我实际上已经按日期排序了这些,但仅仅是为了讨论,我将如何编辑上述查询以获得我描述的结果?
答案 0 :(得分:3)
查看以下问题:
Can I Comma Delimit Multiple Rows Into One Column?
Is it possible to concatenate column values into a string using CTE?
答案 1 :(得分:1)
此问题最干净的解决方案是依赖于数据库。 Lentine的链接显示了非常丑陋的Oracle和SQL Server解决方案以及一个干净的MySQL解决方案。 PostgreSQL中的答案也很简单。
SELECT ticket_number, string_agg(remarks, ', ')
FROM
AT_DeviceReplacement_Tickets tickets
INNER JOIN
AT_DeviceReplacement_Tickets_History history
ON tickets.Ticket_Number = history.Ticket_Number
GROUP BY tickets.ticket_number;
(请注意,示例代码中有ticket_number和TicketNumber。)
我的猜测是Oracle和SQL Server(1)具有类似的聚合函数或(2)具有定义自己的聚合函数的能力。 [对于MySQL,等效聚合称为GROUP_CONCAT。]您使用的是什么数据库?