2012-03-19 58 views
0

嗨亲爱的各位朋友,SQL交叉选项卡功能

我想问一两件事有关SQL交叉表function.Currently,我使​​用SQL 2008 Express的版本,我的表结构如下图所示。

UserID  Str_Value 
1    A 
1    B 
1    C 
2    A 
2    B 
3    D 
3    E 

我想得到这样的结果。

UserID  Str_Value 
1    A,B,C 
2    A,B 
3    D,E 

我不想使用cursor.Is那里有任何功能吗?
请给我正确的方式,我真的很感激。

谢谢。

最好的问候,

+2

这已经被问过很多很多次,你可以发表评论ORDER BY T1.Str_Value如果没有必要,并设置为nvarchar(500)大小,做标记的SQL服务器和群CONCAT的 – Lamak 2012-03-19 16:29:29

+2

可能重复一个快速搜索[模拟MS SQL Server 2005中的group_concat MySQL函数?](http://stackoverflow.com/questions/451415/simulating-group-concat-mysql-function-in-ms-sql-server-2005) – Lamak 2012-03-19 16:30:33

回答

3

希望这有助于。如需要

SELECT DISTINCT T1.UserId, 
Stuff(
     (SELECT N', ' + T2.Str_Value 
     FROM t T2 
     WHERE T2.userId = T1.userid 
     ORDER BY T2.Str_Value 
     FOR XML PATH(''),TYPE).value('text()[1]','nvarchar(500)'),1,2,N'') 
     AS Str_Value 
FROM t T1 
3
SELECT UserId, LEFT(Str_Value, LEN(Str_Value) - 1) AS Str_Value 
FROM YourTable AS extern 
CROSS APPLY 
(
    SELECT Str_Value + ',' 
    FROM YourTable AS intern 
    WHERE extern.UserId = intern.UserId 
    FOR XML PATH('') 
) pre_trimmed (Str_Value) 
GROUP BY UserId, Str_Value 
1

试试这个:

SELECT DISTINCT 
    t1.UserID, 
    Values = SUBSTRING((SELECT (', ' + t2.Str_Value) 
        FROM dbo.Users t2 

        ORDER BY 
         t2.Str_Value 
        FOR XML PATH('') 
       ), 3, 4000)FROM dbo.Users t1 
GROUP BY t1.UserID 
+0

'stuff(str, 1,1,'')'而不是'substring' – 2012-03-19 17:47:54

0
create table #temp 
(
    userid int, 
    str_value varchar(1) 
) 

insert into #temp values (1, 'A') 
insert into #temp values (1, 'B') 
insert into #temp values (1, 'C') 

insert into #temp values (2, 'A') 
insert into #temp values (2, 'B') 

insert into #temp values (3, 'D') 
insert into #temp values (3, 'E') 

select userid, left(x.str_value, len(x.str_value) -1) as str_value 
from #temp t 
cross apply 
(
    select str_value + ',' 
    FROM #temp t1 
    where t.userid = t1.userid 
    for xml path('') 
) x (str_value) 
group by userid, x.str_value 

drop table #temp