假设我有查询:
SELECT Foo FROM Bar
返回
富
A
B
C
我到底是什么:
的富
A,B,C
因此,所有行中的所有值都已折叠为一行(逗号是可选的)。
有没有办法使用select语句来执行此操作,因为我不想使用游标?
答案 0 :(得分:2)
DECLARE @foos VARCHAR(4000)
SELECT @foos = COALESCE(@foos + ',', '') + Foo FROM Bar
SELECT @foos AS Foo
答案 1 :(得分:1)
SELECT
(
SELECT
CASE
WHEN ROW_NUMBER() OVER(ORDER BY bar) = 1 THEN ''
ELSE ', '
END + CAST(bar AS VARCHAR)
FROM foo
ORDER BY bar
FOR XML PATH('')
)
答案 2 :(得分:0)
这应该让你开始。
DECLARE @r VARCHAR(8000)
SELECT @r = (SELECT DISTINCT Foo + ', ' FROM Bar FOR XML PATH(''))
IF @r IS NOT NULL AND @r <> '' SET @r = SUBSTRING(@r, 1, LEN(@r)-1)
SELECT @r
答案 3 :(得分:0)
尝试以下
declare @joined varchar(max)
set @joined = ''
select @joined = @joined + IsNull(Foo + ',', '')
from Bar (nolock)
--; Drop last "," if necessary
set @joined = substring(@joined, 1, len(@joined) - (case when len(@joined) > 0 then 1 else 0 end))
select @joined as foo
答案 4 :(得分:0)
尝试查看this answer。
它做了类似你想要做的事情。
答案 5 :(得分:0)
select max(a),max(b),max(c) from
(
select 'a' as a,null as b,null as c
union
select null,'b',null
union
select null,null,'c'
) as x