获取1行3行数据

时间:2015-09-29 06:52:53

标签: sql .net sql-server-2008 c#-4.0

我的记录如下:

aid  cmpyname  rid  imgpath

 1      abc     1   ~/img/aa.jpg:~/img/bb.jpg:~/img/cc.jpg:
 2      abc     1   ~/img/dd.jpg:~/img/ee.jpg:~/img/ff.jpg:

 3      xyz     2   ~/img/gg.jpg:~/img/hh.jpg:~/img/ii.jpg:
 4      xyz     2   ~/img/jj.jpg:~/img/kk.jpg:~/img/ll.jpg:

我想得到的内容显示在下方 - 但在一个查询中

cmpyname  rid  imgpath

  abc     1   ~/img/aa.jpg:~/img/bb.jpg:~/img/cc.jpg:~/img/dd.jpg:~/img/ee.jpg:~/img/ff.jpg:

  xyz     2   ~/img/gg.jpg:~/img/hh.jpg:~/img/ii.jpg:~/img/jj.jpg:~/img/kk.jpg:~/img/ll.jpg:

我该怎么办?我没有提供任何关系所以请记住。

谢谢和问候

4 个答案:

答案 0 :(得分:3)

select max(cmpyname) as cmpyname, rid,
stuff((
    select imgpath
    from Records t1
    where t1.rid = t2.rid
    order by t1.aid
    for xml path(''), type).value('.', 'varchar(max)'), 1, 0, ''
) as imgpath
from Records t2
group by rid;

http://sqlfiddle.com/#!3/da096/4

答案 1 :(得分:1)

这样的事情:

只需粘贴到一个空的查询窗口并执行即可。适应您的需求......

DECLARE @tbl TABLE(aid INT,  cmpyname VARCHAR(100),  rid INT,  imgpath VARCHAR(1000));
INSERT INTO @tbl VALUES
 (1,'abc',1,'~/img/aa.jpg:~/img/bb.jpg:~/img/cc.jpg:')
,(2,'abc',1,'~/img/dd.jpg:~/img/ee.jpg:~/img/ff.jpg:')
,(3,'xyz',2,'~/img/gg.jpg:~/img/hh.jpg:~/img/ii.jpg:')
,(4,'xyz',2,'~/img/jj.jpg:~/img/kk.jpg:~/img/ll.jpg:');

SELECT DISTINCT tbl.cmpyname
      ,tbl.rid
      ,(
            SELECT '' + x.imgpath
            FROM @tbl AS x
            WHERE x.rid=tbl.rid
            FOR XML PATH('')
       ) AS allPaths
FROM @tbl AS tbl

答案 2 :(得分:1)

select distinct rid,imgpath,rid from(
select imgpath=(select imgpath + ', ' AS 'data()' 
FROM tbl_Temp 
where tbl_Temp.rid=rid   FOR XML PATH('')  ) 
,id,cmpyname,rid from tbl_Temp
) as temp

答案 3 :(得分:0)

SELECT DISTINCT B.cmpyname, B.rid,
(
    SELECT imgpath + '' FROM tbl1 AS A WHERE (B.rid = A.rid) FOR XML PATH('')
) AS imgpath

FROM tbl1 AS B