添加多个varchar列(子查询/循环?)

时间:2013-06-12 22:08:18

标签: sql tsql sql-server-2000

我有3张桌子,我正在尝试创建报告......

Table MP (data table)
mID col1    col2
1   data1   data2
2   data3   data4
3   data5   data6

Table MPU (user table)
uID UserName
1   user1
2   user2
3   user3

Table MPR (lookup table)
rID uID mID
1   1   2
2   2   2
3   1   1

这是我需要的基本选择逻辑:

Select
    MP.mID
    ,MP.col1
    ,MP.col2
    ,MPU.UserName --format as 'user1, user2, user3' ...
From MP
left join MPR on MPR.mID  = MP.mID
left join MPU on MPU.uID = MPR.uID

我需要在代码中添加用户名字符串 有些数据行没有用户,有些数据行可能有10个用户 我不希望现在填充多行。

编辑:
注 - SQL 2000

1 个答案:

答案 0 :(得分:0)

我只能为MSSQL 2000建议这种方法:

select
    mID,
    col1,
    col2,
    MAX( CASE seq WHEN 1 THEN UserName ELSE '' END )  +
    MAX( CASE seq WHEN 2 THEN ', '+UserName ELSE '' END ) + 
    MAX( CASE seq WHEN 3 THEN ', '+UserName ELSE '' END ) + 
    MAX( CASE seq WHEN 4 THEN ', '+UserName ELSE '' END ) + 
    MAX( CASE seq WHEN 5 THEN ', '+UserName ELSE '' END ) + 
    MAX( CASE seq WHEN 6 THEN ', '+UserName ELSE '' END ) + 
    MAX( CASE seq WHEN 7 THEN ', '+UserName ELSE '' END ) + 
    MAX( CASE seq WHEN 8 THEN ', '+UserName ELSE '' END ) + 
    MAX( CASE seq WHEN 9 THEN ', '+UserName ELSE '' END ) + 
    MAX( CASE seq WHEN 10 THEN ', '+UserName ELSE '' END ) 

FROM (
    Select
        MP1.mID,
        MP1.col1,
        MP1.col2,
        MPU1.UserName,
        (
            SELECT COUNT(*)
            From MP as MP2
            left join MPR as MPR2 on MPR2.mID  = MP2.mID
            left join MPU as MPU2 on MPU2.uID = MPR2.uID
            WHERE MP2.mID = MP1.mID
            AND MPU2.UserName <= MPU1.UserName
        ) seq
    From MP as MP1
    left join MPR as MPR1 on MPR1.mID  = MP1.mID
    left join MPU as MPU1 on MPU1.uID = MPR1.uID
) t1
GROUP BY mID, col1, col2;