将行转换为 t-sql 中的列 - sql server 2005 [英] converting rows into columns in t-sql - sql server 2005

查看:41
本文介绍了将行转换为 t-sql 中的列 - sql server 2005的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的情况是结构中有一个表

I have situation that I have a table in the structure

ID, name
 1, 'value1'
 1, 'value2'
 2, 'value3'
 2, 'value4'
 1, 'value5'

我想以下列格式显示以上数据

I wanted to show the above data in following format

id , combineName
1  ,'value1','value2', 'value5'
2  ,'value3','value4'

在 SQL Server 2005 中是否有一种简单的方法可以做到这一点,或者我必须运行游标才能做到这一点?

Is there an easy way to do this in SQL Server 2005, or will I have to run cursors to do it?

推荐答案

假设您的数据在 aTable 中:

Assuming your data is in aTable:

create  FUNCTION toCSV (@id int)

RETURNS varchar(100)

AS

BEGIN

DECLARE @List varchar(100)

SELECT @List = COALESCE(@List + ', ', '') + 
   CAST(name AS varchar(10))

FROM aTable

WHERE ID = @id

RETURN(@list)

END;

go

那么:

从表中选择不同的 id,dbo.toCSV(id)

select distinct id, dbo.toCSV(id) from aTable

这篇关于将行转换为 t-sql 中的列 - sql server 2005的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆