我尝试了如下所示
SELECT SUBSTRING(
(
SELECT td.Text + ', ' AS 'data()',
Tda.FirmID
FROM tblData1 tda
INNER JOIN tblData2 Td
ON Tda.ID = Td.ID
GROUP BY
Tda.Enable1,
Tda.ID,
Td.Text
HAVING ISNULL(Enable1, 0) = 1
FOR XML PATH('')
),
1,
10000
) AS Csv
输出:
Landlord Tenant, <FirmID>1</FirmID>NJ Traffic, <FirmID>1</FirmID>
预期输出:应采用表格格式
csv FirmID
Landlord Tenant, NJ Traffic 1
答案 0 :(得分:0)
省略子查询中的别名并尝试:
SELECT STUFF((SELECT ', ' + td.Text
FROM tblData2 Td
WHERE ISNULL(Enable1, 0) = 1
FOR XML PATH('')
), 1, 2, '') AS Csv,
MAX(Tda.FirmID)
FROM tblData1 tda;
您也无法在子查询中选择多个列。毕竟,目的是将值组合到单个列中。 select
中的多个值创建一列,但字符串中包含多个XML标记。
您也不需要子查询中的group by
。
答案 1 :(得分:0)
我使用 COALESCE
得到了结果DECLARE @Text VARCHAR(MAX)
DECLARE @ID NUMERIC(18,0)
SELECT @Text = COALESCE(@Text + ', ', '') +
CAST(td.Text AS VARCHAR(MAX)),@ID = MAX(tda.FirmID)
FROM tblData1 tda
INNER JOIN tblData2 Td
ON Tda.ID=Td.ID
GROUP BY
Tda.Enable,
Tda.FirmID,Td.Text
HAVING ISNULL(Enable,0)=1
SELECT @Text AS Text,@ID AS ID
输出:
text ID
Landlord Tenant, NJ Traffic 1