现在,我有一个像这样的SQL查询:
SELECT X, Y FROM POINTS
它会返回如下结果:
X Y
----------
12 3
15 2
18 12
20 29
我想在一行中返回结果,如下所示(适合在HTML< AREA>标记中使用):
XYLIST
----------
12,3,15,2,18,12,20,29
有没有办法只使用SQL?
答案 0 :(得分:70)
感谢快速而有用的答案!
我刚刚发现了另一种快速方法:
SELECT STUFF(( SELECT ',' + X + ',' + Y
FROM Points
FOR
XML PATH('')
), 1, 1, '') AS XYList
归功于这个人:
答案 1 :(得分:25)
DECLARE @XYList varchar(MAX)
SET @XYList = ''
SELECT @XYList = @XYList + CONVERT(varchar, X) + ',' + CONVERT(varchar, Y) + ','
FROM POINTS
-- Remove last comma
SELECT LEFT(@XYList, LEN(@XYList) - 1)
答案 2 :(得分:11)
使用COALESCE
技巧,您不必担心尾随逗号:
DECLARE @XYList AS varchar(MAX) -- Leave as NULL
SELECT @XYList = COALESCE(@XYList + ',', '') + CONVERT(varchar, X) + ',' + CONVERT(varchar, Y)
FROM POINTS
答案 3 :(得分:4)
从SQL 2017开始,您可以使用double total = 0;
for (int i = n; i >= 1; i-=4)
{
total = Math.Sqrt(total + i);
}
STRING_AGG
https://docs.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-2017
答案 4 :(得分:1)
DECLARE @s VarChar(8000)
SET @s = ''
SELECT @s = @s + ',' + CAST(X AS VarChar) + ',' + CAST(Y AS VarChar)
FROM POINTS
SELECT @s
摆脱领先的逗号