转置查询创建节点(SQL Server 2008)

时间:2011-12-12 16:31:30

标签: sql sql-server-2008 pivot transpose

我终于找到了执行查询以获取一行中一个内容的所有ID(以逗号分隔)。

以下查询完成了诀窍:

您不需要查看查询,因为它已经完成了应该执行的操作。

SELECT 
    taxonomy_item_id, 
    SUBSTRING(
      (SELECT ', ' + CAST(taxonomy_id AS varchar) AS Expr1
       FROM taxonomy_item_tbl AS t2
       WHERE (t1.taxonomy_item_id = taxonomy_item_id) AND (taxonomy_language_id = 2067)
       ORDER BY taxonomy_item_id, taxonomy_id FOR XML PATH('')
      ), 1, 1000) AS taxonomy_ids
FROM 
    taxonomy_item_tbl AS t1
WHERE 
    (taxonomy_language_id = 2067) AND (taxonomy_item_id = 180555)
GROUP BY 
    taxonomy_item_id

唯一的问题是我得到的数据结果:

180555  |   <Expr1>, 404</Expr1><Expr1>, 405</Expr1><Expr1>, 723</Expr1><Expr1>, 1086</Expr1><Expr1>, 1087</Expr1><Expr1>, 1118</Expr1><Expr1>, 1124</Expr1><Expr1>, 1126</Expr1>

我不需要<Expr1>个节点。有没有办法删除它?如果我在查询中删除AS Expr1,则会自动将其添加回来

由于

1 个答案:

答案 0 :(得分:0)

如果你不想要<Expr1> - 那就不要求它了!

你有:

(SELECT ', ' + CAST(taxonomy_id AS varchar) AS Expr1

AS Expr1导致<Expr1>被添加 - 所以只是没有那个表达式。

尝试

SELECT 
    taxonomy_item_id, 
    SUBSTRING(
      (SELECT ', ' + CAST(taxonomy_id AS VARCHAR) 
       FROM dbo.taxonomy_item_tbl AS t2
       WHERE t1.taxonomy_item_id = taxonomy_item_id
       AND taxonomy_language_id = 2067
       ORDER BY taxonomy_item_id, taxonomy_id 
       FOR XML PATH('')
      ), 1, 1000) AS taxonomy_ids
FROM 
    dbo.taxonomy_item_tbl AS t1
WHERE 
    taxonomy_language_id = 2067
    AND taxonomy_item_id = 180555
GROUP BY 
    taxonomy_item_id