如何将多行合并为一行,并具有包含逗号分隔值的列?
示例:最初,我的SQLresult使用一个简单的select脚本返回以下内容
select order_no, item_no, item_description
from orders...
order_no item_no item_description
1234 5 toaster
1234 6 hair dryer相反,我想将结果返回到下面的列表中(以与item_nos相同的顺序列出item_description
order_no item_nos item_descriptions
1234 5, 6 toaster, hair dryer 我可以像这样返回结果吗?
order_no item_nos_descriptions
1234 5 - toaster, 6 - hair dryer顺便说一句,我正在使用SQL2008...
发布于 2011-09-21 14:03:28
查看group_concat函数(docs)。
select
order_no,
group_concat(item_no ORDER BY item_nos ASC SEPARATOR ', ') as item_nos,
group_concat(item_description ORDER BY item_no ASC SEPARATOR ', ')
as item_descriptions
from orders
group by order_no会给出类似这样的东西:
order_no item_nos item_descriptions
1234 5, 6 toaster, hair dryer 对于您请求的第二个表单,它将如下所示:
select
order_no,
group_concat( concat(item_no,' - ',item_description
ORDER BY item_no ASC SEPARATOR ', ')
as item_nos_descriptions
from orders
group by order_no发布于 2011-09-21 15:42:07
对于SQL Server2005和更高版本,以下是我通常不使用递归CTE执行此操作的方法
DECLARE @T TABLE
(
order_no int,
item_no int,
item_description nvarchar(50)
)
INSERT INTO @T VALUES (1234, 5, 'toaster')
INSERT INTO @T VALUES (1234, 6, 'hair dryer')
SELECT order_no,
STUFF(
(
SELECT ', ' + CAST(item_no AS VARCHAR) AS [text()]
FROM @T As MyItem
WHERE MyItem.order_no = MyTable.order_no
FOR XML PATH('')
), 1, 2, '' ) AS item_nos,
STUFF(
(
SELECT ', ' + CAST(item_no AS VARCHAR) AS [text()]
FROM @T As MyItem
WHERE MyItem.order_no = MyTable.order_no
FOR XML PATH('')
), 1, 2, '' ) AS item_descriptions
FROM @T AS MyTable
GROUP BY order_no这会产生以下结果:
Result Set (1 item)
order_no | item_nos | item_descriptions |
1234 | 5, 6 | 5, 6这个东西去掉了字符串中的最后一个',‘。
另一种方法是使用递归CTE,但我认为上面的方法可以做到……
发布于 2011-09-21 13:42:49
我认为如果可以的话,你应该注意@pst。
也就是说,大多数关系数据库都有执行此操作的功能。在MySQL中,它是group_concat。在甲骨文中,它是wm_concat。在PostgreSQL中,它是string_agg。请注意,它相当不标准化。
要使用它,您可以这样做:
SELECT order_no, string_agg(item_description, ',')
FROM orders
INNER JOIN line_items ON line_item.order_id = order.id
GROUP BY order_no;注意,并不是所有的数据库都有从CSV返回到行的方法。我知道PostgreSQL可以做到这一点。我希望甲骨文能够做到这一点,但没有检查过,我相当确定MySQL不能,但可能是错误的。
https://stackoverflow.com/questions/7495027
复制相似问题