[英]T-SQL - string concatenation
Hope someone can help - I am a novice SQL hacker (and very bad at it indeed!) 希望有人可以提供帮助 - 我是新手SQL黑客(确实非常糟糕!)
I have two tables on SQL Server 2005 TABLE 1 and TABLE2: 我在SQL Server 2005表1和表2上有两个表:
TABLE1 表格1
COL1 COL2
1 10
2 20
3 30
4 10
4 20
5 20
6 30
7 10
7 20
TABLE2 TABLE2
COL1 COL2
10 A
20 B
30 C
COL2 in TABLE2 is a character representation of the numerical data in COL2 TABLE1. TABLE2中的COL2是COL2 TABLE1中数值数据的字符表示。 I hope this is understandable?
我希望这是可以理解的吗?
I have worked out how to select COL1 and COL2 from TABLE1 and concatenate the results to show this: 我已经研究了如何从TABLE1中选择COL1和COL2并连接结果以显示:
COL1 COL2Concat
1 10
2 20
3 30
4 10, 20
5 20
6 30
7 10, 20, 30
Using this: 使用这个:
SELECT COL1,
STUFF(( SELECT ',' + CAST(a.COL2 AS VARCHAR(255)) AS [text()]
FROM TABLE1 a
WHERE a.COL1 = b.COL1
ORDER BY a.COL2
FOR
XML PATH('')
), 1, 1, '') AS COL2Concat
FROM TABLE1 b
GROUP BY COL1
ORDER BY COL1
But now I'd like to try and get the same result except use the data in COL2 TABLE2... ie: 但是现在我想尝试获得相同的结果,除了使用COL2 TABLE2中的数据...即:
COL1 COL2Concat
1 A
2 B
3 C
4 A, B
5 B
6 C
7 A, B, C
Any ideas - I'm stuck to be honest as I have tried modifying the STUFF query, but it never seems to come out right... 任何想法 - 我坚持诚实,因为我尝试修改STUFF查询,但它似乎永远不会出现...
you could try... 你可以试试......
SELECT COL1,
STUFF(( SELECT ',' + CAST((SELECT COL2
FROM TABLE2
WHERE TABLE2.COL1 = a.COL1) AS VARCHAR(255)) AS [text()]
FROM TABLE1 a
WHERE a.COL1 = b.COL1
ORDER BY a.COL2
FOR
XML PATH('')
), 1, 1, '') AS COL2Concat
FROM TABLE1 b
GROUP BY COL1
ORDER BY COL1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.