转置查询varchar bigint转换

时间:2011-12-12 14:12:14

标签: sql sql-server-2008 pivot transpose

我有以下sql查询(这是一个用于获取逗号分隔表的转置查询)

    SELECT CAST ((SELECT taxonomy_id + ','
                  FROM content
                  FOR XML PATH('')) AS bigint) AS NewTaxonomytableName

但我得到Error converting data type varchar to bigint. 表格taxonomy_idbigint

有什么想法吗?

更新:

SELECT CAST ((SELECT CAST(taxonomy_id AS varchar) + ',' AS Expr1 FROM taxonomy_item_tbl FOR XML PATH('')) AS varchar) AS Expr1

运行它给了我一行。

但实际上它不适合我。它需要逗号分隔特定content_id的taxonomy_id。

一个例子:

content_id taxonomy_id
1          15 
1          16 
5          24 
5          19

需要:

content_id taxonomy_id
1          15,16
5          24,19

我真的坚持了8个小时。如果有人可以帮助我,我会非常感激...

由于

2 个答案:

答案 0 :(得分:1)

问题在于您没有将taxonomy_id转换为bigint,而是将逗号分隔的列表转换为bigint。

请改为尝试:

SELECT CAST ((SELECT CAST(taxonomy_id as varchar) + ','
              FROM content
              FOR XML PATH('')) AS varchar(max)) AS NewTaxonomytableName

修改 好吧,因为我不完全确定你的表结构,你可能需要玩这个以获得你想要的,但理论是正确的。

SELECT DISTINCT c.content_id,
    CAST((SELECT CAST(taxonomy_id as varchar) + ','
          FROM content
          WHERE content_id = c.content_id
          FOR XML PATH('')) AS varchar(max)) AS taxonomy_ids
FROM content c

答案 1 :(得分:1)

declare @T table
(
  content_id int,
  taxonomy_id int
)

insert into @T values
(1,          15), 
(1,          16), 
(5,          24), 
(5,          19)


select T1.content_id,
       stuff((select ','+cast(T2.taxonomy_id as varchar(20))
              from @T as T2       
              where T1.content_id = T2.content_id
              for xml path(''),  type).value('.', 'varchar(max)'), 1, 1, '') as taxeconomy_id
from @T as T1
group by T1.content_id

结果:

content_id  taxeconomy_id
----------- -------------
1           15,16
5           24,19