下面给出了三个表格。 (为了方便起见,我用数据插入编码了它们)。我需要在@TableA
中的每一行的逗号分隔列表中获取ValueBDECLARE @TableA TABLE(IDA INT, ValueA VARCHAR(20))
DECLARE @TableB TABLE(IDB INT, ValueB VARCHAR(20))
DECLARE @TableC TABLE(IDC INT, fIDA INT, fIDB INT)
INSERT INTO @TableA(IDA,ValueA)
SELECT 1, 'aaa'
UNION
SELECT 2, 'bbb'
UNION
SELECT 3, 'ccc'
UNION
SELECT 4, 'ddd'
INSERT INTO @TableB(IDB, ValueB)
SELECT 1, 'Option1'
UNION
SELECT 2, 'Option2'
UNION
SELECT 3, 'Option3'
INSERT INTO @TableC(IDC,fIDA,fIDB)
SELECT 1,1,1
UNION
SELECT 2,1,3
UNION
SELECT 3,3,1
UNION
SELECT 4,3,2
UNION
SELECT 5,4,3
预期输出为:
IDA | ValueA| Options
-----------------------------------
1 | aaa | Option1,Option3
2 | bbb | NULL
3 | ccc | Option1,Option2
4 | ddd | Option3
在SQLServer 2005中使用TSQL如何获得上述预期输出
答案 0 :(得分:3)
这是上述问题的解决方案:
SELECT ta.IDA, ta.ValueA, stuff((
SELECT ', ' + cast(ValueB as varchar(max))
FROM @TableB tb INNER JOIN @TableC tc ON tc.fIDB = tb.IDB
WHERE tc.fIDA = ta.IDA
FOR XML PATH('')
), 1, 2, '') AS Options
FROM @TableA ta