2

我有一张桌子说ProjectMaster

  Id       ProjectName
  1         A
  2         B
  3         C

另一张桌子ProjectMeter

 Id   ProjectId   MeterNumber
 1      1          #0001
 2      1          #0002
 3      1          #0003 
 4      2          #0004
 5      2          #0005 
 6      3          #0006

我希望有以下输出

ProjectName   MeterNumbers 
 A             #0001, #0002, #0003
 B             #0004, #0005
 C             #0006

我试过这个这个,但无法解决我的问题。我不能使用表变量。

我已经编写了一个存储过程,它从许多joined表中获取数据。ProjectMaster 也恰好加入了这些表之一。现在需要从 ProjectMeter 获取数据,这样,每一行都连接了对应于该列中 ProjectId 的 ProjectMeter.MeterNumber。

现在,我得到所有行中所有仪表编号的串联列表。

I cannot use CURSOR, TABLE variable , Temp TABLE 

(我希望仍然可以为我的事业做点什么)

请帮忙.....

4

3 回答 3

4

尝试这个:

SELECT projectname, STUFF((SELECT distinct ', ' + meternumber 
              from projectmeter m
              where p.id = m.projectid
            FOR XML PATH(''), TYPE

            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'') MeterNumbers
from projectmaster p

请参阅带有演示的 SQL Fiddle

于 2012-08-29T13:57:44.110 回答
1

同样在 MS SQL 中,您可以使用带有 CTE 的递归查询来做到这一点。

这是一个SQLFiddle 演示

;with t1 as (
 select t.*,
        cast(meternumber as varchar(max)) as m2,
        0 as level
     from ProjectMeter t 
     where not exists 
        (select id 
                from ProjectMeter l 
          where l.id<t.id and l.ProjectId=t.ProjectID 
        )
 union all
 select b.*,
        cast(c.m2+','+b.MeterNumber as varchar(max)) as m2,
        c.level+1 as level
     from ProjectMeter b
         inner join t1 c
             on (c.id < b.id) and (b.ProjectID=c.ProjectId)

)

select pm.ProjectName as ProjectName, 
       t1.m2 as MeterNumbers 
      from t1 
      inner join
        (select ProjectId,max(level) ml 
              from t1 
          group by ProjectId
        ) t2  
            on (t1.ProjectId=t2.ProjectID) and (t1.level=t2.ml)
       left join ProjectMaster pm 
           on (t1.ProjectId=pm.Id)
order by t1.ProjectID
于 2012-08-29T15:02:56.960 回答
1
DECLARE @ProjectMaster AS TABLE
    (
      ID INT IDENTITY(1, 1) ,
      ProjectName VARCHAR(2)
    )
DECLARE @ProjectMeter AS TABLE
    (
      ID INT IDENTITY(1, 1) ,
      ProjectID INT ,
      MeterNumber VARCHAR(50)
    )

INSERT  INTO @ProjectMaster
        ( ProjectName )
VALUES  ( 'A' )

INSERT  INTO @ProjectMeter
        ( ProjectID, MeterNumber )
VALUES  ( 1, '#0001' )
INSERT  INTO @ProjectMeter
        ( ProjectID, MeterNumber )
VALUES  ( 1, '#0002' )

SELECT pMaster.ID, STUFF(( SELECT  ',' + MeterNumber
                FROM    @ProjectMeter
              FOR
                XML PATH('')
              ), 1, 1, '') AS 'Concat Result'
FROM    @ProjectMeter pMeter
        INNER JOIN @ProjectMaster pMaster ON pMaster.ID = pMeter.ProjectID
GROUP BY pMaster.ID

我在这里使用了表变量,但是您肯定只需要删除@,因为我使用了与您指定的相同的表名吗?不确定这是否可以?:)

于 2012-08-29T13:58:17.343 回答